object oriented programming classes and objects dr. mike spann [email protected]

58
Object Oriented Programming Classes and Objects Classes and Objects Dr. Mike Spann Dr. Mike Spann [email protected] [email protected]

Upload: felicity-berry

Post on 26-Dec-2015

228 views

Category:

Documents


2 download

TRANSCRIPT

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

Object Oriented Programming

Classes and ObjectsClasses and Objects

Dr. Mike SpannDr. Mike Spann

[email protected]@bham.ac.uk

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

Contents Introducing Object Oriented ProgrammingIntroducing Object Oriented Programming Classes, Types and ObjectsClasses, Types and Objects Building our own classesBuilding our own classes ConstructorsConstructors PropertiesProperties Implementation/Interface and encapsulationImplementation/Interface and encapsulation Method arguments – call by value and by referenceMethod arguments – call by value and by reference Operator overloadingOperator overloading SummarySummary

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

Introducing Object Oriented Programming

Object oriented programming (OOP) is THE Object oriented programming (OOP) is THE programming methodology for designing complex programming methodology for designing complex systemssystems

OOP essentially is about the use of re-useable OOP essentially is about the use of re-useable software components called objectssoftware components called objects

These objects can be prebuilt by third party These objects can be prebuilt by third party vendors to ‘plug in’ to our application or can be vendors to ‘plug in’ to our application or can be developed by ourselvesdeveloped by ourselves Perhaps building on existing objectsPerhaps building on existing objects

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

Introducing Object Oriented Programming

There are good reasons why building our application There are good reasons why building our application out of such objects has major advantagesout of such objects has major advantages We can We can abstract outabstract out the complex state and the complex state and

behaviour of individual objectsbehaviour of individual objects Only the interface between the objects in our Only the interface between the objects in our

application is importantapplication is important We can use prebuilt objects such as FCL objectsWe can use prebuilt objects such as FCL objects

We are able to extend these objects to meet our We are able to extend these objects to meet our own needsown needs

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

Introducing Object Oriented Programming

Drive

TransmissionGearboxEngineElectronics

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

Classes, Types and Objects The FCL consists of classes, interfaces structures and The FCL consists of classes, interfaces structures and

enumerated typesenumerated types Collectively known as Collectively known as typestypes We have already seen some examples of classesWe have already seen some examples of classes

System, Console, FormSystem, Console, FormClasses are reference typesClasses are reference typesValue types are known as structuresValue types are known as structures

We can create our own classes, interfaces, structures We can create our own classes, interfaces, structures and enumerated typesand enumerated types

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

Classes, Types and Objects

The process of using a type to create an object is The process of using a type to create an object is called called instantiationinstantiation

In C#, C++, and Java the In C#, C++, and Java the newnew keyword is used keyword is used

We could create many We could create many CarCar objects but there is objects but there is only one only one CarCar class class

Car myCar = new Car(“Peugeot 207”);

Class Object

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

Classes, Types and Objects

Car myCar = new Car(“Peugeot 207”);

Car myColleaguesCar = new Car(“Ford Focus”);

myCar

myColleaguesCar

Peugeot 207

Ford Focus

Car

Car

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

Building our own classes

We can easily build our own classes which We can easily build our own classes which comprise comprise methodsmethods and and fieldsfields Simply stated, methods are functions which Simply stated, methods are functions which

describe the describe the behaviourbehaviour of objects of the class of objects of the class Fields are themselves types (either objects or Fields are themselves types (either objects or

primitive types) which describe the primitive types) which describe the statestate of the of the objectobject

We create a class using the We create a class using the class{} class{} clauseclause

Class myClass{

// Methods and fields}

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

Building our own classes

The class can optionally exist in its own namespaceThe class can optionally exist in its own namespace

The full class name then becomes The full class name then becomes name.myClassname.myClass If no namespace is specified, it exists in the If no namespace is specified, it exists in the default default

namespacenamespace

namespace name{

Class myClass{

// Methods and fields}

}

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

Building our own classes AA StudentInfo StudentInfo class used to store student records information class used to store student records information

2 (public) methods2 (public) methods StudentInfo(..)StudentInfo(..) – a method with the same name as the class, known as – a method with the same name as the class, known as

a a constructorconstructor

Used for initializing Used for initializing StudentInfo StudentInfo objectsobjects

printStudentInfoprintStudentInfo()()

Outputs the records information to the consoleOutputs the records information to the console

3 (private) instance fields3 (private) instance fields namename idNumberidNumber addressaddress

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

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;

}

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

Building our own classes

Keyword Keyword privateprivate means only methods in means only methods in the the StudentInfoStudentInfo class can access these fields class can access these fields

Keyword Keyword publicpublic means the method can be means the method can be called from any other method in any other called from any other method in any other classclass

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

Building our own classes

StudentInfo

String nameint idNumberString address

private

publicStudentInfo()printStudentInfo()

Accessed only by

Accessed from anywhere

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

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

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

Building our own classes

So far in the So far in the StudentInfoStudentInfo class, we have 3 private class, we have 3 private instance fieldsinstance fields namename idNumberidNumber addressaddress

These instance fields are known as These instance fields are known as non-staticnon-static instance fieldsinstance fields Each Each StudentInfoStudentInfo object has its own separate object has its own separate

copy of these three fieldscopy of these three fields

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

Building our own classes We can also have We can also have static instance fieldsstatic instance fields which represent which represent

class wide class wide informationinformation For example we might want to keep the total number of For example we might want to keep the total number of

students registered as a static field of students registered as a static field of StudentInfoStudentInfo Not sensible to keep this in each Not sensible to keep this in each StudentInfoStudentInfo object object

Can be accessed by methods of Can be accessed by methods of StudentInfoStudentInfoBut not vice versa – non-static methods cannot access But not vice versa – non-static methods cannot access

static instance fields!static instance fields!Can be get and set using Can be get and set using staticstatic properties in the usual properties in the usual

wayway

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

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;

}

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

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

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

Building our own classes

StudentInfo s1=new StudentInfo(....);

StudentInfo s2=new StudentInfo(....);

s1 s2

name=“John Smith"idNumber=3429address= "21 Bristol Rd"

name=“Alan Jones“idNumber= 5395address="15 Bournbrook Rd"

class StudentInfo

private String name;private int idNumber;private String addressprivate static numberRegistered=2;

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

Constructors

A constructor is a special method of a class used to A constructor is a special method of a class used to initialize the fields of each object createdinitialize the fields of each object created The C# compiler knows you are defining a The C# compiler knows you are defining a

constructor method when you give a method the constructor method when you give a method the exact same name as the type itselfexact same name as the type itself

The constructor method is automatically called by the The constructor method is automatically called by the runtime when an instance is created runtime when an instance is created

It is possible for constructors to be overloaded so that It is possible for constructors to be overloaded so that an object can be created with a variety of starting dataan object can be created with a variety of starting data

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

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;

}

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

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}

}

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

Constructors

The default constructor makes default initializations The default constructor makes default initializations for typefor type Reference types default to nullReference types default to null Integers default to zeroIntegers default to zero It is It is automaticallyautomatically provided by the compiler provided by the compiler

should no other constructor be givenshould no other constructor be given Normally, use is made of the Normally, use is made of the thisthis reference to reference to

enforce user defined default initializationsenforce user defined default initializations thisthis is an implicit reference to the outer object is an implicit reference to the outer object

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

Constructors

StudentInfo

String nameint idNumberString address

private

publicStudentInfo( )

printStudentInfo( )

this

this

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

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;

}

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

Properties

Properties are class members which can be accessed Properties are class members which can be accessed using field access syntax, but they are really method using field access syntax, but they are really method callscalls Essentially more convenient syntax than method Essentially more convenient syntax than method

callscalls A property has a name and a type, and comes with a A property has a name and a type, and comes with a

read function and a write function named read function and a write function named getget and and setset respectivelyrespectively Generally for each private field, we declare one Generally for each private field, we declare one

public property public property

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

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;

}

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

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

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

Properties

We could validate the data before setting it, We could validate the data before setting it, for example:for example:

public int ID{ get { return idNumber; }

set { if (value > 0) idNumber = value; else idNumber = -1; }}

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

Implementation/Interface and encapsulation Generally, instance fields are privateGenerally, instance fields are private

They represent the They represent the implementationimplementation of the class (or of the class (or the object internal state)the object internal state)

Methods are generally publicMethods are generally public They represent the They represent the interfaceinterface to the class to the class The define how objects can be used The define how objects can be used

The separation of a class into public/private is a key The separation of a class into public/private is a key feature of object-oriented programmingfeature of object-oriented programming Sometimes known as Sometimes known as encapsulationencapsulation

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

Implementation/Interface and encapsulation

The implementation of a class is specified in the The implementation of a class is specified in the private instance fields private instance fields They are hidden from outside the classThey are hidden from outside the class

The interface to the class is specified by the public The interface to the class is specified by the public methodsmethods They can be accessed from anywhere They can be accessed from anywhere

The implementation may change but the interface The implementation may change but the interface must stay the samemust stay the same

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

Implementation/Interface and encapsulation ExampleExample

Class Class PointPoint represents the position in the represents the position in the 2D (x-y) plane2D (x-y) plane

The x and y coordinates are accessed The x and y coordinates are accessed through the properties through the properties XX and and YY

Note that these are declared as publicNote that these are declared as public

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

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

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

Implementation/Interface and encapsulation

We can use this class in an application to We can use this class in an application to represent a polygon as an array of points represent a polygon as an array of points (vertices)(vertices) Could be for a computer graphics applicationCould be for a computer graphics application

For example, to compute the perimeter of the For example, to compute the perimeter of the polygon, we need to access the coordinates of polygon, we need to access the coordinates of the verticesthe vertices We do this through the properties We do this through the properties XX and and YY

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

Implementation/Interface and encapsulationclass Polygonclass Polygon{{

public Polygon() {…}public Polygon() {…}

public double perimeter()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;nn=n%numVertices;

// Access vertices coordinates through properties// Access vertices coordinates through properties int xv1= vertices[n-1].X; int xv1= vertices[n-1].X;

int yv1=vertices[n-1]. Y;int yv1=vertices[n-1]. Y; int xv=vertices[nn].X; int xv=vertices[nn].X;

int yv=vertices[nn].Y;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 Point[] vertices;private int numVertices;private int numVertices;

}}

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

Implementation/Interface and encapsulation

The idea behind encapsulation is that changing the The idea behind encapsulation is that changing the implementation implementation of of PointPoint will not change the will not change the implementation of the implementation of the PolygonPolygon class because class because Point Point objects are accessed through public properties or objects are accessed through public properties or methodsmethods The users of The users of PointPoint do not even need to know about do not even need to know about

itit PointPoint is a re-useable software component is a re-useable software component

Example – we can implement Example – we can implement PointPoint objects using a objects using a polar coordinate representationpolar coordinate representation

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

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

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

Method arguments – call by value and by reference

We have already seen that we can have We have already seen that we can have reference types reference types (usually references to (usually references to objects) and objects) and value type value type (usually primitive (usually primitive types)types)

There are similarly two ways to pass There are similarly two ways to pass arguments to class methodsarguments to class methods Pass by valuePass by value Pass by referencePass by reference

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

Method arguments – call by value and by reference

As in C++ and Java, pass by value creates a local copy in the called As in C++ and Java, pass by value creates a local copy in the called methodmethod The called method can’t change the value of the argument in the The called method can’t change the value of the argument in the

calling methodcalling method Pass by reference involves passing a (copy) of the argument (object) Pass by reference involves passing a (copy) of the argument (object)

reference into the called methodreference into the called method The called method can then change the state of the argument The called method can then change the state of the argument

(object) in the calling method(object) in the calling method Also C# provides a keyword Also C# provides a keyword outout to create an output parameter to create an output parameter

This indicates that the arguments will be passed to the call This indicates that the arguments will be passed to the call method by reference which will assign a value to the original method by reference which will assign a value to the original variable from the calling methodvariable from the calling method

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

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

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

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 uninitializedsq.callByOut(out z);

Console.WriteLine("After call by z: z = " + z); }}

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

Method arguments – call by value and by reference

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

Method arguments – call by value and by reference

When we pass objects into methods, we are passing When we pass objects into methods, we are passing the object reference the object reference But the object reference is normally passed by valueBut the object reference is normally passed by value In other words we are passing a copy of the In other words we are passing a copy of the

reference into the methodreference into the method The object in the calling method can still be altered The object in the calling method can still be altered

in the called methodin the called methodBut the reference in the calling method can’t be But the reference in the calling method can’t be

altered – it always refers to the same objectaltered – it always refers to the same object

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

anObject

Calling method

Called method

Method arguments – call by value and by reference

ref to anObject

Copy of ref to anObject

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

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 Such a technique can lead to serious errors

if not used wiselyif not used wiselyThe called method assumes control of The called method assumes control of

the object in the calling methodthe object in the calling method However it can also be a subtle capability However it can also be a subtle capability

for experienced programmersfor experienced programmers

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

Method arguments – call by value and by reference

anObject

Calling method

Called method

ref to anObject

ref to ref to anObject

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

Method arguments – call by value and by reference

In this example, the called method has a reference In this example, the called method has a reference to the reference to the objectto the reference to the object In this case it could alter the original referenceIn this case it could alter the original reference

For example, it could change it to reference For example, it could change it to reference a different objecta different object

This would then cause a memory leak which This would then cause a memory leak which would be ultimately garbage collectedwould be ultimately garbage collected

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

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

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

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

}}

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

Method arguments – call by value and by reference

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

Method arguments – call by value and by reference In the call by ref case, we have created a memory leak by In the call by ref case, we have created a memory leak by

altering the original referencealtering the original reference

StudentInfo

Calling method

Called method

s John Smith 342921 Bristol Rd

StudentInfo

no name0no fixed abode

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

Operator overloading

Operator overloading is a convenient way of Operator overloading is a convenient way of manipulating objectsmanipulating objects Through the use of standard operators rather Through the use of standard operators rather

than normal method callsthan normal method calls It simply involves implementing methods of It simply involves implementing methods of

classes the objects of which we want to classes the objects of which we want to manipulatemanipulate

Overloading the standard arithmetic operators is Overloading the standard arithmetic operators is by far the most commonby far the most common

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

Operator overloading

We need to provide class methods We need to provide class methods operator opoperator op operator +operator + operator –operator – operator *operator * etcetc

Methods overloading a binary operator take 2 Methods overloading a binary operator take 2 arguments corresponding to the 2 operandsarguments corresponding to the 2 operands

Similarly for unary operandsSimilarly for unary operands The method must be The method must be publicpublic and and staticstatic

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

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

}

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

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

}}

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

Operator overloading

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

Summary We have looked at the basis of classes and objectsWe have looked at the basis of classes and objects

How do declare our own classesHow do declare our own classes How to create objects of those classesHow to create objects of those classes

We have looked at the constituents of a classWe have looked at the constituents of a class MethodsMethods Instance fieldsInstance fields PropertiesProperties

We have looked at the idea of encapsulation as a key feature of object We have looked at the idea of encapsulation as a key feature of object orientationorientation

We have looked at passing arguments by value and by reference to class We have looked at passing arguments by value and by reference to class methodsmethods

We have looked at a simple example of operator overloadingWe have looked at a simple example of operator overloading