580 likes | 593 Views
Learn the fundamentals of object-oriented programming, including classes, objects, constructors, properties, and encapsulation. Gain a solid foundation in OOP concepts and principles.
E N D
Object Oriented Programming Classes and Objects Dr. Mike Spann m.spann@bham.ac.uk
Contents • Introducing Object Oriented Programming • Classes, Types and Objects • Building our own classes • Constructors • Properties • Implementation/Interface and encapsulation • Method arguments – call by value and by reference • Operator overloading • Summary
Introducing Object Oriented Programming • Object oriented programming (OOP) is THE programming methodology for designing complex systems • OOP essentially is about the use of re-useable software components called objects • These objects can be prebuilt by third party vendors to ‘plug in’ to our application or can be developed by ourselves • Perhaps building on existing objects
Introducing Object Oriented Programming • There are good reasons why building our application out of such objects has major advantages • We can abstract out the complex state and behaviour of individual objects • Only the interface between the objects in our application is important • We can use prebuilt objects such as FCL objects • We are able to extend these objects to meet our own needs
Introducing Object Oriented Programming Drive Transmission Gearbox Engine Electronics
Classes, Types and Objects • The FCL consists of classes, interfaces structures and enumerated types • Collectively known as types • We have already seen some examples of classes • System, Console, Form • Classes are reference types • Value types are known as structures • We can create our own classes, interfaces, structures and enumerated types
Classes, Types and Objects Car myCar = new Car(“Peugeot 207”); Class Object The process of using a type to create an object is called instantiation In C#, C++, and Java the new keyword is used We could create many Car objects but there is only one Car class
Classes, Types and Objects Car myCar = new Car(“Peugeot 207”); Car myColleaguesCar = new Car(“Ford Focus”); Car Peugeot 207 myCar Car Ford Focus myColleaguesCar
Building our own classes Class myClass { // Methods and fields } • We can easily build our own classes which comprise methods and fields • Simply stated, methods are functions which describe the behaviour of objects of the class • Fields are themselves types (either objects or primitive types) which describe the state of the object • We create a class using the class{} clause
Building our own classes namespace name { Class myClass { // Methods and fields } } • The class can optionally exist in its own namespace • The full class name then becomes name.myClass • If no namespace is specified, it exists in the default namespace
Building our own classes • AStudentInfo class used to store student records information • 2 (public) methods • StudentInfo(..) – a method with the same name as the class, known as a constructor • Used for initializing StudentInfoobjects • printStudentInfo() • Outputs the records information to the console • 3 (private) instance fields • name • idNumber • address
Building our own classes using System; public class StudentInfo { public StudentInfo(string n, int id, string a) { name=n; idNumber=id; address=a; } public void printStudentInfo() { Console.WriteLine(name + " " + idNumber + " " + address); } private string name; private intidNumber; private string address; }
Building our own classes Keyword private means only methods in the StudentInfo class can access these fields Keyword public means the method can be called from any other method in any other class
Building our own classes Accessed from anywhere StudentInfo public StudentInfo() printStudentInfo() private String name int idNumber String address Accessed only by
Building our own classes using System; class StudentInfoTest { static void Main(string[] args) { StudentInfo si1=new StudentInfo("John Smith", 3429, "21 Bristol Rd"); StudentInfo si2=new StudentInfo("Alan Jones", 5395, "15 Bournbrook Rd"); si1. printStudentInfo(); si2.printStudentInfo(); } }
Building our own classes • So far in the StudentInfo class, we have 3 private instance fields • name • idNumber • address • These instance fields are known as non-static instance fields • Each StudentInfo object has its own separate copy of these three fields
Building our own classes • We can also have static instance fields which represent class wide information • For example we might want to keep the total number of students registered as a static field of StudentInfo • Not sensible to keep this in each StudentInfo object • Can be accessed by methods of StudentInfo • But not vice versa – non-static methods cannot access static instance fields! • Can be get and set using static properties in the usual way
public class StudentInfo { public StudentInfo(string n, int id, string a) { name=n; idNumber=id; address=a; } public void printStudentInfo() { Console.WriteLine(name + " " + idNumber + " " + address); Console.WriteLine(numberRegistered + " students “); } // Name, Address and ID properties ....... public static intNumberRegistered { get { return numberRegistered; } set { numberRegistered = value; } } private static intnumberRegistered; private string name; private intidNumber; private string address; }
Building our own classes class StudentInfoTest { static void Main(string[] args) { StudentInfo si1=new StudentInfo("John Smith",3429, "21 Bristol Rd"); StudentInfo si2=new StudentInfo("Alan Jones", 5395, "15 Bournbrook Rd"); StudentInfo.NumberRegistered = 2; si1.printStudentInfo(); } }
class StudentInfo private String name; private int idNumber; private String address private static numberRegistered=2; name=“Alan Jones“ idNumber= 5395 address="15 Bournbrook Rd" name=“John Smith" idNumber=3429 address= "21 Bristol Rd" s1 s2 Building our own classes StudentInfo s1=new StudentInfo(....); StudentInfo s2=new StudentInfo(....);
Constructors • A constructor is a special method of a class used to initialize the fields of each object created • The C# compiler knows you are defining a constructor method when you give a method the exact same name as the type itself • The constructor method is automatically called by the runtime when an instance is created • It is possible for constructors to be overloaded so that an object can be created with a variety of starting data
Constructors using System; public class StudentInfo { public StudentInfo() {} // default constructor public StudentInfo(string n, int id, string a) { name=n; idNumber=id; address=a; } public void printStudentInfo() { Console.WriteLine(name + " " + idNumber + " " + address); } private string name; private intidNumber; private string address; }
Constructors using System; public class StudentInfoTest { public static void Main(string[] args) { StudentInfo s1=new StudentInfo(“John Smith”,12345, “53 Bristol Rd”); StudentInfo s2=new StudentInfo(); // Default constructor } }
Constructors • The default constructor makes default initializations for type • Reference types default to null • Integers default to zero • It is automatically provided by the compiler should no other constructor be given • Normally, use is made of the this reference to enforce user defined default initializations • this is an implicit reference to the outer object
Constructors StudentInfo this public StudentInfo( ) printStudentInfo( ) this private String name int idNumber String address
Constructors using System; public class StudentInfo { public StudentInfo() {this(“No name”, 0, “Birmingham University”} public StudentInfo(string n, int id, string a) { name=n; idNumber=id; address=a; } public void printStudentInfo() { Console.WriteLine(name + " " + idNumber + " " + address); } private string name; private intidNumber; private string address; }
Properties • Properties are class members which can be accessed using field access syntax, but they are really method calls • Essentially more convenient syntax than method calls • A property has a name and a type, and comes with a read function and a write function named get and set respectively • Generally for each private field, we declare one public property
public class StudentInfo { public StudentInfo(string n, int id, string a) { name=n; idNumber=id; address=a; } public void printStudentInfo() { Console.WriteLine(name + " " + idNumber + " " + address); } public string Name { get { return name; } set { name = value; } } public string Address { get { return address; } set { address = value; } } public int ID { get { return idNumber; } set { idNumber = value; } } private string name; private intidNumber; private string address; }
Properties class StudentInfoTest { static void Main(string[] args) { StudentInfo si1=new StudentInfo(null, 0, null); StudentInfo si2=new StudentInfo("Alan Jones", 5395,"15 Bournbrook Rd"); // Access through properties // Uses set{} si1.ID = 3429; si1.Name = "John Smith"; si1.Address = "21 Bristol Rd"; // Uses get{} int id = si2.ID; string name=si2.Name; string address=si2.Address; } }
Properties public int ID { get { return idNumber; } set { if (value > 0) idNumber = value; else idNumber = -1; } } We could validate the data before setting it, for example:
Implementation/Interface and encapsulation • Generally, instance fields are private • They represent the implementation of the class (or the object internal state) • Methods are generally public • They represent the interface to the class • The define how objects can be used • The separation of a class into public/private is a key feature of object-oriented programming • Sometimes known as encapsulation
Implementation/Interface and encapsulation • The implementation of a class is specified in the private instance fields • They are hidden from outside the class • The interface to the class is specified by the public methods • They can be accessed from anywhere • The implementation may change but the interface must stay the same
Implementation/Interface and encapsulation • Example • Class Point represents the position in the 2D (x-y) plane • The x and y coordinates are accessed through the properties X and Y • Note that these are declared as public
Implementation/Interface and encapsulation public class Point { public Point(int x, int y) { xpos = x; ypos = y; } public int X { get{ return xpos; } set { xpos=value; } } public int Y { get{ return ypos; } set { ypos=value; } } private intxpos, ypos; }
Implementation/Interface and encapsulation • We can use this class in an application to represent a polygon as an array of points (vertices) • Could be for a computer graphics application • For example, to compute the perimeter of the polygon, we need to access the coordinates of the vertices • We do this through the properties X and Y
Implementation/Interface and encapsulation class Polygon { public Polygon() {…} public double perimeter() { double pm=0; intnn; for (int n=1; n<numVertices; n++) { nn=n%numVertices; // Access vertices coordinates through properties int xv1= vertices[n-1].X; int yv1=vertices[n-1]. Y; int xv=vertices[nn].X; intyv=vertices[nn].Y; pm+=(Math.sqrt((xv1-xv)*(xv1-xxv)+(yv1-yv)*(yv1-yv))); } return pm; } private Point[] vertices; private intnumVertices; }
Implementation/Interface and encapsulation • The idea behind encapsulation is that changing the implementation of Point will not change the implementation of the Polygon class because Point objects are accessed through public properties or methods • The users of Point do not even need to know about it • Point is a re-useable software component • Example – we can implement Point objects using a polar coordinate representation
public class Point { public Point(int x, int y) { r=System.Math.Sqrt(x*x+y*y) theta=Math.Atan2((double)y,(double)x); } public double X { get{return (r*Math.Cos(theta));} } public double Y { get { return (r * Math.Sin(theta)); } } private double r; private double theta; }
Method arguments – call by value and by reference • We have already seen that we can have reference types (usually references to objects) and value type (usually primitive types) • There are similarly two ways to pass arguments to class methods • Pass by value • Pass by reference
Method arguments – call by value and by reference • As in C++ and Java, pass by value creates a local copy in the called method • The called method can’t change the value of the argument in the calling method • Pass by reference involves passing a (copy) of the argument (object) reference into the called method • The called method can then change the state of the argument (object) in the calling method • Also C# provides a keyword out to create an output parameter • This indicates that the arguments will be passed to the call method by reference which will assign a value to the original variable from the calling method
Method arguments – call by value and by reference public class Square { public void callByVal(int x) { x = x * x; } public void callByRef(ref int x) { x = x * x; } public void callByOut(out int x) { x = 3; x = x * x; } }
Method arguments – call by value and by reference using System; class SquareTest { static void Main(string[] args) { Square sq = new Square(); int y = 5; int z; sq.callByVal(y); Console.WriteLine("After call by val: y = " + y); sq.callByRef(ref y); Console.WriteLine("After call by ref: y = " + y); // z uninitialized sq.callByOut(out z); Console.WriteLine("After call by z: z = " + z); } }
Method arguments – call by value and by reference • When we pass objects into methods, we are passing the object reference • But the object reference is normally passed by value • In other words we are passing a copy of the reference into the method • The object in the calling method can still be altered in the called method • But the reference in the calling method can’t be altered – it always refers to the same object
Method arguments – call by value and by reference anObject ref to anObject Calling method Called method Copy of ref to anObject
Method arguments – call by value and by reference • But we can pass a reference to a reference (!!) • Such a technique can lead to serious errors if not used wisely • The called method assumes control of the object in the calling method • However it can also be a subtle capability for experienced programmers
Method arguments – call by value and by reference anObject ref to anObject Calling method Called method ref to ref to anObject
Method arguments – call by value and by reference • In this example, the called method has a reference to the reference to the object • In this case it could alter the original reference • For example, it could change it to reference a different object • This would then cause a memory leak which would be ultimately garbage collected
Method arguments – call by value and by reference public class myStudentRecordsApplication { public static void setIDpassByVal(StudentInfo s) { s.ID = 9999; s = new StudentInfo("no name", 0, "no fixed abode"); } public static void setIDpassByRef(ref StudentInfo s) { s.ID = 9999; s = new StudentInfo("no name", 0, "no fixed abode"); } }
Method arguments – call by value and by reference class StudentInfoTest { static void Main(string[] args) { StudentInfo s=new StudentInfo("John Smith",3429, "21 Bristol Rd"); Console.Writeline(“Original object”) s.printStudentInfo(); myStudentRecordsApplication.setIDpassByVal(s); Console.Writeline(“Pass object ref by value”); s.printStudentInfo(); myStudentRecordsApplication.setIDpassByRef(ref s); Console.Writeline(“Pass object ref by reference”); s.printStudentInfo(); } }