Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object Oriented Programming Classes and Objects Dr. Mike Spann

Similar presentations


Presentation on theme: "Object Oriented Programming Classes and Objects Dr. Mike Spann"— Presentation transcript:

1 Object Oriented Programming Classes and Objects Dr. Mike Spann m.spann@bham.ac.uk

2 Contents Introducing Object Oriented Programming Introducing Object Oriented Programming Classes, Types and Objects Classes, Types and Objects Building our own classes Building our own classes Constructors Constructors Properties Properties Implementation/Interface and encapsulation Implementation/Interface and encapsulation Method arguments – call by value and by reference Method arguments – call by value and by reference Operator overloading Operator overloading Summary Summary

3 Introducing Object Oriented Programming Object oriented programming (OOP) is THE programming methodology for designing complex systems 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 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 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

4 Introducing Object Oriented Programming There are good reasons why building our application out of such objects has major advantages 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

5 Introducing Object Oriented Progr amming Drive Transmission Gearbox Engine Electronics

6 Classes, Types and Objects The FCL consists of classes, interfaces structures and enumerated types 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 We can create our own classes, interfaces, structures and enumerated types

7 Classes, Types and Objects The process of using a type to create an object is called instantiation The process of using a type to create an object is called instantiation In C#, C++, and Java the new keyword is used In C#, C++, and Java the new keyword is used We could create many Car objects but there is only one Car class We could create many Car objects but there is only one Car class Car myCar = new Car(“Peugeot 207”); ClassObject

8 Classes, Types and Objects Car myCar = new Car(“Peugeot 207”); Car myColleaguesCar = new Car(“Ford Focus”); myCar myColleaguesCar Peugeot 207 Ford Focus Car

9 Building our own classes We can easily build our own classes which comprise 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 We create a class using the class{} clause Class myClass { // Methods and fields }

10 Building our own classes The class can optionally exist in its own namespace 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 namespace name { Class myClass { // Methods and fields }

11 Building our own classes A StudentInfo class used to store student records information A StudentInfo class used to store student records information 2 (public) methods 2 (public) methods  StudentInfo(..) – a method with the same name as the class, known as a constructor  Used for initializing StudentInfo objects  printStudentInfo()  Outputs the records information to the console 3 (private) instance fields 3 (private) instance fields  name  idNumber  address

12 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 int idNumber; private string address; }

13 Building our own classes Keyword private means only methods in the StudentInfo class can access these fields 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 Keyword public means the method can be called from any other method in any other class

14 Building our own classes StudentInfo String name int idNumber String address private public StudentInfo() printStudentInfo() Accessed only by Accessed from anywhere

15 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(); }

16 Building our own classes So far in the StudentInfo class, we have 3 private instance fields 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 These instance fields are known as non- static instance fields  Each StudentInfo object has its own separate copy of these three fields

17 Building our own classes We can also have static instance fields which represent class wide information 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

18 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 int NumberRegistered { get { return numberRegistered; } set { numberRegistered = value; } } private static int numberRegistered; private string name; private int idNumber; private string address; }

19 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(); }

20 Building our own classes StudentInfo s1=new StudentInfo(....); StudentInfo s2=new StudentInfo(....); s1s2 name=“John Smith" idNumber=3429 address="21 Bristol Rd" name=“Alan Jones“ idNumber= 5395 address="15 Bournbrook Rd " class StudentInfo private String name; private int idNumber; private String address private static numberRegistered=2;

21 Constructors A constructor is a special method of a class used to initialize the fields of each object created 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 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 It is possible for constructors to be overloaded so that an object can be created with a variety of starting data

22 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 int idNumber; private string address; }

23 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 }

24 Constructors The default constructor makes default initializations for type 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 Normally, use is made of the this reference to enforce user defined default initializations  this is an implicit reference to the outer object

25 Constructors StudentInfo String name int idNumber String address private public StudentInfo( ) printStudentInfo( ) this

26 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 int idNumber; private string address; }

27 Properties Properties are class members which can be accessed using field access syntax, but they are really method calls 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 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

28 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 int idNumber; private string address; }

29 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

30 We could validate the data before setting it, for example: We could validate the data before setting it, for example: public int ID { get { return idNumber; } set { if (value > 0) idNumber = value; else idNumber = -1; }

31 Implementation/Interface and encapsulation Generally, instance fields are private Generally, instance fields are private  They represent the implementation of the class (or the object internal state) Methods are generally public 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 The separation of a class into public/private is a key feature of object-oriented programming  Sometimes known as encapsulation

32 Implementation/Interface and encapsulation The implementation of a class is specified in the private instance fields 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 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 The implementation may change but the interface must stay the same

33 Implementation/Interface and encapsulation Example 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

34 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 int xpos, ypos; }

35 Implementation/Interface and encapsulation We can use this class in an application to represent a polygon as an array of points (vertices) 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 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

36 Implementation/Interface and encapsulation class Polygon { public Polygon() {…} public double perimeter() { double pm=0; int nn; double pm=0; int nn; for (int n=1; n<numVertices; n++) for (int n=1; n<numVertices; n++) {nn=n%numVertices; // Access vertices coordinates through properties int xv1= vertices[n-1].X; int xv1= vertices[n-1].X; int yv1=vertices[n-1]. Y; int xv=vertices[nn].X; int xv=vertices[nn].X; int yv=vertices[nn].Y; pm+=(Math.sqrt((xv1-xv)*(xv1-xxv)+(yv1-yv)*(yv1-yv))); pm+=(Math.sqrt((xv1-xv)*(xv1-xxv)+(yv1-yv)*(yv1-yv))); } return pm; return pm;} private Point[] vertices; private int numVertices; }

37 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 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 Example – we can implement Point objects using a polar coordinate representation

38 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; }

39 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) 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 There are similarly two ways to pass arguments to class methods  Pass by value  Pass by reference

40 Method arguments – call by value and by reference As in C++ and Java, pass by value creates a local copy in the called method 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 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 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

41 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; }

42 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); }

43 Method arguments – call by value and by reference

44 When we pass objects into methods, we are passing the object 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

45 anObject Calling method Called method Method arguments – call by value and by reference ref to anObject Copy of ref to anObject

46 Method arguments – call by value and by reference But we can pass a reference to a 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

47 Method arguments – call by value and by reference anObject Calling method Called method ref to anObject ref to ref to anObject

48 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 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

49 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"); }

50 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(); }

51 Method arguments – call by value and by reference

52 In the call by ref case, we have created a memory leak by altering the original reference In the call by ref case, we have created a memory leak by altering the original reference StudentInfo Calling method Called method s John Smith 3429 21 Bristol Rd StudentInfo no name 0 no fixed abode

53 Operator overloading Operator overloading is a convenient way of manipulating objects Operator overloading is a convenient way of manipulating objects  Through the use of standard operators rather than normal method calls It simply involves implementing methods of classes the objects of which we want to manipulate It simply involves implementing methods of classes the objects of which we want to manipulate Overloading the standard arithmetic operators is by far the most common Overloading the standard arithmetic operators is by far the most common

54 Operator overloading We need to provide class methods operator op We need to provide class methods operator op  operator +  operator –  operator *  etc Methods overloading a binary operator take 2 arguments corresponding to the 2 operands Methods overloading a binary operator take 2 arguments corresponding to the 2 operands Similarly for unary operands Similarly for unary operands The method must be public and static The method must be public and static

55 using System; public class ComplexNumber { private double real,imaginary; public double Real { get { return real; } public double Imaginary { get { return imaginary; } public ComplexNumber(double a, double b) { real=a; imaginary=b; } public override string ToString() { return string.Format("({0} {1} {2}i)", real, (imaginary <0 ? "-" : "+"), Math.Abs(imaginary)); } public static ComplexNumber operator+(ComplexNumber z1, ComplexNumber z2) { return new ComplexNumber(z1.real + z2.real, z1.imaginary + z2.imaginary); } public static ComplexNumber operator*(ComplexNumber z1, ComplexNumber z2) { return new ComplexNumber(z1.real * z2.real - z1.imaginary * z2.imaginary, z1.real * z2.imaginary + z2.real * z1.imaginary); }

56 Operator overloading using System; public class ComplexNumberTest { static void Main(string[] args) { ComplexNumber z1, z2; z1 = new ComplexNumber(1.0, 2.0); z2 = new ComplexNumber(3.0, 5.0); ComplexNumber z3 = z1 + z2; ComplexNumber z4 = z1 * z2; Console.WriteLine("{0} + {1}= {2}", z1, z2, z3); Console.WriteLine("{0} * {1}= {2}", z1, z2, z4); }

57 Operator overloading

58 Summary We have looked at the basis of classes and objects We have looked at the basis of classes and objects  How do declare our own classes  How to create objects of those classes We have looked at the constituents of a class We have looked at the constituents of a class  Methods  Instance fields  Properties We have looked at the idea of encapsulation as a key feature of object orientation We have looked at the idea of encapsulation as a key feature of object orientation We have looked at passing arguments by value and by reference to class methods We have looked at passing arguments by value and by reference to class methods We have looked at a simple example of operator overloading We have looked at a simple example of operator overloading


Download ppt "Object Oriented Programming Classes and Objects Dr. Mike Spann"

Similar presentations


Ads by Google