inheritance and polymorphism

47
Object Oriented Programming Inheritance and Inheritance and Polymorphism Polymorphism

Upload: vincentius-yosephat-suryo

Post on 16-Dec-2015

220 views

Category:

Documents


0 download

DESCRIPTION

C# Programing

TRANSCRIPT

  • Object Oriented Programming

    Inheritance and Polymorphism

  • ContentsBase classes and derived classesExample a BankAccount classPolymorphism and Object Oriented ProgrammingAbstract classesGeneric ProgrammingPolymorphism and OOPSummary

  • Base classes and derived classes

    Inheritance is a fundamental requirement of oriented programmingIt allows us to create new classes by refining existing classesEssentially a derived class can inherit data members of a base classThe behaviour of the derived class can be refined by redefining base class member functions or adding new member functionA key aspect of this is polymorphism where a classes behaviour can be adapted at run-time

  • Base classes and derived classesWe can think of many examples in real life of how a (base) class can be refined to a set of (derived) classesFor example a Polygon class can be refined to be a Quadrilateral which can be further refined to be a RectangleWe can think of these classes as following an IS-A relationshipA Quadrilateral IS-A PolygonA Rectangle IS-A Quadrilateral

  • Base classes and derived classes

    Base classDerived classShapeTriangle, Circle, RectangleAccountCurrent, Deposit StudentUndergraduate, PostgaduateVehicleCar, Truck, BusFilterLow-pass, Band-pass, High-pass

  • Example a BankAccount class

    An BankAccount base class models basic information about a bank accountAccount holderAccount numberCurrent balanceBasic functionalityWithdraw moneyDeposit money

  • public class BankAccount{ private int accountNumber;private string accountHolder;private int balance;

    public BankAccount(int n,string name ,int b) { accountNumber = n; accountHolder = name; balance = b; }

    public int AccountNumber { // accountNumber property} public string AccountHolder { // accounHolder property} public int Balance { // balance property} public void withdraw(int amount) { if (balance>amount) balance-=amount;}

    public void deposit(int amount) { balance+=amount;}}

  • Example a BankAccount classWe can consider refinements to our Account classCurrentAccountCan have an overdraft facilityNo interest paidDepositAccountPays interest on any balanceNo overdraft facility

  • Example a BankAccount classWe will create our refined classes using inheritance from the BankAccount base classClasses CurrentAccount and DepositAccount inherit the basic attributes (private members) of accountaccountNumberaccountHolderbalanceAlso, new attributes are added overdraftFacility interestRate

  • Example a BankAccount classIn order to implement the derived classes, we need to consider private/public access between base and derived classespublic member functions of the base class become public member functions of the derived classprivate members of the base class cannot be accessed from the derived classObvious otherwise encapsulation could be easily broken by inheriting from the base classBegs the question, how do we initialise derived class objects?

  • Example a BankAccount classBase class methods and properties are accessed through the base keywordbase(.....) refers to the base class constructorbase.aMethod(.....) refers to a method of the base classbase.aProperty refers to a property of the base class

  • class CurrentAccount : BankAccount{private int overdraftFacility;

    public CurrentAccount(int n, string name, int b, int ov) : base(n, name, b) { overdraftFacility = ov; }

    public override void withdraw(int amount) { if (base.Balance - amount > -overdraftFacility) base.Balance -= amount;}}

    class DepositAccount : BankAccount{ private float interestRate;

    public DepositAccount(int n, string name, int b, float rate) : base( n, name,b) { interestRate = rate; }

    float calcInterest() { float interest = base.Balance * interestRate; base.Balance += (int)(interest); return interest;} }

  • Example a BankAccount classaccountNumberaccountHolderbalancedeposit()withdraw()overdraftFacilitywithdraw()interestRatecalcInterest()accountNumberaccountHolderbalancedeposit()withdraw()CurrentAccountDepositAccount

  • Example a BankAccount classWe can see that in both derived classes we need to access the balance instance fieldWe can do this directly (without using a public method or property) by making balance a protected member of the base classA protected class member is one that can be accessed by public member functions of the class as well as public member functions of any derived classIts half way between private and publicEncapsulation is then broken for classes in the inheritance hierarchy and thus must be used where performance issues are critical

  • Example a BankAccount class

    Class memberCan be accessed fromprivatepublic member functions of same classprotectedpublic member functions of same class and derived classespublicAnywhere

  • public class BankAccount{ private int accountNumber;private string accountHolder;protected int balance;

    public BankAccount(int n,string name ,int b) { accountNumber = n; accountHolder = name; balance = b; }

    public int AccountNumber { // accountNumber property} public string AccountHolder { // accounHolder property} public int Balance { // balance property} public void withdraw(int amount) { if (balance>amount) balance-=amount;}

    public void deposit(int amount) { balance+=amount;}}

  • class CurrentAccount : BankAccount{private int overdraftFacility;

    public CurrentAccount(int n, string name, int b, int ov) : base(n, name, b) { overdraftFacility = ov; }

    public override void withdraw(int amount) { if (balance - amount > -overdraftFacility)// balance is protected balance -= amount;}}

    class DepositAccount : BankAccount{ private float interestRate;

    public DepositAccount(int n, string name, int b, float rate) : base( n, name,b) { interestRate = rate; }

    float calcInterest() { float interest = balance * interestRate; balance += (int)(interest); return interest;} }

  • Polymorphism and Object Oriented ProgrammingPolymorphism is the key concept in object oriented programmingPolymorphism literally means many formsEssentially we are able to get many different types of object behaviour from a single reference typeThis enables us to write easily extensible applications

  • Polymorphism and Object Oriented ProgrammingFor example in a computer game that simulates the movement of animals we can send move commands to different types of animalWe send the commands via an animal reference which is the base class for the different animal typesBut each type behaves differently once it receives the commandSuch an approach leads to a readily extendable application

  • Polymorphism and Object Oriented ProgramminganimalMoveApplication

  • Polymorphism and Object Oriented ProgrammingPolymorphism is implemented through references to objectsWe can assign base class object references to any derived class object

    BankAccount acc1 = new CurrentAccount(12345, "John Smith", 1000, 500);

    BankAccount acc2 = new DepositAccount(54321, "Bill Jones", 2000, 5.0);

  • Polymorphism and Object Oriented Programmingacc1CurrentAccount500withdraw()12345John Smith1000deposit()withdraw()

  • Polymorphism and Object Oriented Programmingacc2DepositAccount5.0calcInterest()54321Bill Jones2000deposit()withdraw()

  • Polymorphism and Object Oriented ProgrammingWe can see that in the case of the reference to a CurrentAccountObject object, method withdraw() is overidden in the derived classThe question is, which one is called at runtime?public class BankAccountTest{ static void Main(string[] args) { BankAccount acc1 = new CurrentAccount(12345, "John Smith,1000, 500);

    acc1.withdraw(250);// Which withdraw()? }}

  • Polymorphism and Object Oriented ProgrammingaccountNumberaccountHolderbalancedeposit()withdraw()overdraftFacilitywithdraw()acc1CurrentAccountWhich one is called?

  • Polymorphism and Object Oriented ProgrammingClearly the behaviour of the object to the withdraw message is importantThe derived class behaviour takes into account the overdraft facilityWe must look at the definitions of the withdraw() method in the base and derived classesThe base class withdraw() method is overridden by the derived class method if the base class method is declared as virtual and the derived class method is declared as override

  • Polymorphism and Object Oriented Programmingpublic class CurrentAccount : BankAccount{private int overdraftFacility;

    public CurrentAccount(n, name, b) {}

    public override void withdraw(int amount) { if (balance - amount > -overdraftFacility) balance -= amount;

    } }public class BankAccount{//

    public virtual void withdraw(int amount) { if (balance - amount > -overdraftFacility) balance -= amount; } }

  • Polymorphism and Object Oriented ProgrammingBecause withdraw() in the derived class is declared as an override function of the virtual function in the base class, the correct behaviour is obtainedpublic class BankAccountTest{ static void Main(string[] args) { BankAccount acc1 = new CurrentAccount(12345, "John Smith,1000, 500);

    acc1.withdraw(250);// Calls the CurrentAccount withdraw() method }}

  • Polymorphism and Object Oriented ProgrammingIn Java, polymorphism (overriding the base class implementation) is the default behaviourIn C++, the virtual keyword is used but no override keywordC# also has a keyword sealed for a base class method which cant be overridenMethods can also be declared override and sealed indicating that they override a base class method but cant themselves be overriden

  • Abstract classesIn our example classes, the withdraw() method of our BankAccount was declared as a virtual functionWe were able to provide a sensible implementation of this functionThis implementation could be regarded as default behaviour if the function was not overridden in derived classes

  • Abstract classespublic class BankAccountTest{ static void Main(string[] args) { BankAccount acc1 = new CurrentAccount(12345, "John Smith,1000, 500);

    acc1.withdraw(250);// Calls the CurrentAccount withdraw() method

    BankAccount acc2 = new DepositAccount(54321, Bill Jones,2000, 5.0);

    acc2.withdraw(100);// Calls the BankAccount withdraw() method

    }}If the method called cant be resolved in the derived class, it is delegated back to the default base class method

  • Abstract classesAbstract classes arise when there is no sensible implementation of the virtual functions in the base classBase class virtual functions are always overridden by derived class implementationsIn this case, we simply declare the virtual function as abstract but provide no implementationA class containing at least one abstract function must be declared an abstract class

  • Abstract classesAs an example, suppose we wanted to design a hierarchy of shape classes for a computer graphics applicationShape is an abstract conceptThere is no sensible way we can implement functions to draw a shape or compute the area of a shapeIt is natural to make such functions abstractWe can derive concrete classes from shape and provide implementations in the override functions

  • Abstract classespublic abstract class Shape{ private int xpos; private int ypos;

    public abstract void draw();public abstract double area(); public virtual void move(int x, int y) { xpos+=x; ypos+=y; } }

  • Abstract classespublic class Square : Shape{ private int side;

    public Square(int s) {side=s;}

    public override void draw() { }

    public override double area() { return side*side; }}

    public class Circle : Shape{ private int radius;

    public Circle(int r) { radius = r; }

    public override void draw() { }

    public override double area() { return System.Math.PI*radius*radius;}}

  • Abstract classesWe cant create Shape objects but we can declare Shape references and assign them to derived class objectsusing System;

    class ShapeTest{ static void Main(string[] args) { Shape sq = new Square(10); Shape c = new Circle(5);

    System.Console.WriteLine("Area of square= " + sq.area()); System.Console.WriteLine("Area of circle= " + c.area()); }}

  • Abstract classesWe can regard abstract classes as a glue which binds related classes together and where we dont have to worry about implementational detailsThey just have to present a common interface

    ShapeCircleSquareTriangledraw()

    area().......

  • Generic programmingGeneric programming refers to performing operations on different types using a single piece of codeExamples include the application of searching and sorting algorithms to different data typesIn Java, this is done using polymorphism and the fact that all types are ultimately derived from a superclass objectIn C++ it is normally done using templatesC# provides both mechanisms for generic programmingWe will look at an example of generic searching using polymorphism

  • Generic programmingSuppose we want a generic search algorithm to search for any kind of object in an arrayClass object provides an Equals() method to test whether one object is equal to anotherSimply checks if the 2 object references point to the same area of memoryNot very useful in practiceWe need to provide an Equals() method in the class of the object we are searching forPolymorphism does the rest!

  • Generic ProgrammingIn the following example we are searching for a BankAccount object in an array The search is based on the account numberClass SearchAlg provides a linearSearch method which carries out the searchWe have provided an implementation of Equals() in class BankAccount which overrides the Equals() method in object

  • public class BankAccount{ private int accountNumber;private string accountHolder;private int balance;

    public BankAccount(int n,string name ,int b) { accountNumber = n; accountHolder = name; balance = b; }

    public int AccountNumber { // accountNumber property} public string AccountHolder { // accounHolder property} public int Balance { // balance property} public void withdraw(int amount) { if (balance>amount) balance-=amount;}

    public void deposit(int amount) { balance+=amount;}

    public override bool Equals(object obj){ BankAccount b = (BankAccount) obj; return (accountNumber==b.accountNumber);}}

  • Generic Programmingusing System;

    public class SearchAlg{public static int linearSearch(object[] a, object b){ int n=a.Length; for (int i=0; i

  • using System;

    public class BankAccountTest{static void Main(string[] args) { BankAccount[] b = new BankAccount[3];

    b[0]=new BankAccount(12345, "John Smith",100); b[1]=new BankAccount(13579, "Bill Jones",200); b[2]=new BankAccount(87654, "Paul Brown",300); BankAccount bt=new BankAccount(13579, "JonesB", 700); int index=SearchAlg.linearSearch(b,bt); Console.WriteLine("Acount found at index " + index); }}

    Generic Programming

  • Polymorphism and OOPPolymorphism is a key feature of object oriented programmingComplex systems are able to be easily extended The extendibility is provided by defining new classes within an inheritance hierarchyObjects of these new classes are accessed through a base class referenceThese objects add new behaviours to the system through a common interface to the application (the base class virtual functions)

  • Polymorphism and OOPFor example we could extend the list of animals to which we can send move messages in our video game applicationEach animal is responsible for its own movement code which can easily plug-in to the main applicationThus the application is easily extended with minimal changes to the main application code

  • Polymorphism and OOPMove..animal

  • SummaryWe have looked at how we can extend existing classes through the idea of inheritanceWe have seen how, by accessing derived classes through a base class pointer, object behaviour is determined at run time through polymorphismWe have looked at abstract classes where there is no obvious implementation of base class virtual methodsThese methods are always overriden by derived class methodsWe have looked at the significance of polymorphism in object orientationObject oriented applications are easily extended with additional code mainly confined to new derived classes

    *