Object Oriented Programming Inheritance and Polymorphism Dr Mike
Object Oriented Programming Inheritance and Polymorphism Dr. Mike Spann m. spann@bham. ac. uk
Contents n n n n Base classes and derived classes Example – a Bank. Account class Polymorphism and Object Oriented Programming Abstract classes Generic Programming Polymorphism and OOP Summary
Base classes and derived classes n Inheritance is a fundamental requirement of oriented programming n It allows us to create new classes by refining existing classes n Essentially a derived class can inherit data members of a base class u u The behaviour of the derived class can be refined by redefining base class member functions or adding new member function A key aspect of this is polymorphism where a classes behaviour can be adapted at run-time
Base classes and derived classes n n n We can think of many examples in real life of how a (base) class can be refined to a set of (derived) classes For example a Polygon class can be refined to be a Quadrilateral which can be further refined to be a Rectangle We can think of these classes as following an IS-A relationship u A Quadrilateral IS-A Polygon u A Rectangle IS-A Quadrilateral
Base classes and derived classes Base class Shape Bank Account Student Vehicle Filter Derived class Triangle, Circle, Rectangle Current, Deposit Undergraduate, Postgaduate Car, Truck, Bus Low-pass, Band-pass, High-pass
Example – a Bank. Account class n n An Bank. Account base class models basic information about a bank account u Account holder u Account number u Current balance Basic functionality u Withdraw money u Deposit money
public class { private Bank. Account int account. Number; string account. Holder; int balance; public Bank. Account(int n, string name , int b) { account. Number = n; account. Holder = name; balance = b; } public int Account. Number { // account. Number property} public string Account. Holder { // accoun. Holder 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 Bank. Account class n We can consider refinements to our Account class u u Current. Account t Can have an overdraft facility t No interest paid Deposit. Account t Pays interest on any balance t No overdraft facility
Example – a Bank. Account class n We will create our refined classes using inheritance from the Bank. Account base class n Classes Current. Account and Deposit. Account inherit the basic attributes (private members) of account n u account. Number u account. Holder u balance Also, new attributes are added u overdraft. Facility u interest. Rate
Example – a Bank. Account class n In order to implement the derived classes, we need to consider private/public access between base and derived classes u u public member functions of the base class become public member functions of the derived class private members of the base class cannot be accessed from the derived class t Obvious otherwise encapsulation could be easily broken by inheriting from the base class t Begs the question, how do we initialise derived class objects?
Example – a Bank. Account class n Base class methods and properties are accessed through the base keyword u base(. . . ) refers to the base class constructor u base. a. Method(. . . ) refers to a method of the base class u base. a. Property refers to a property of the base class
class Current. Account : Bank. Account { private int overdraft. Facility; public Current. Account(int n, string name, int b, int ov) : base(n, name, b) { overdraft. Facility = ov; } public override void withdraw(int amount) { if (base. Balance - amount > -overdraft. Facility) base. Balance -= amount; } } class Deposit. Account : Bank. Account { private float interest. Rate; public Deposit. Account(int n, string name, int b, float rate) : base( n, name, b) { interest. Rate = rate; } float calc. Interest() { float interest = base. Balance * interest. Rate; base. Balance += (int)(interest); return interest; } }
Example – a Bank. Account class Current. Account Deposit. Account account. Number account. Holder balance deposit() withdraw() overdraft. Facility interest. Rate withdraw() calc. Interest()
Example – a Bank. Account class n We can see that in both derived classes we need to access the balance instance field n We can do this directly (without using a public method or property) by making balance a protected member of the base class n A 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 class u u Its half way between private and public Encapsulation is then broken for classes in the inheritance hierarchy and thus must be used where performance issues are critical
Example – a Bank. Account class Class member Can be accessed from private public member functions of same class protected public member functions of same class and derived classes Anywhere public
public class Bank. Account { private int account. Number; private string account. Holder; protected int balance; public Bank. Account(int n, string name , int b) { account. Number = n; account. Holder = name; balance = b; } public int Account. Number { // account. Number property} public string Account. Holder { // accoun. Holder property} public int Balance { // balance property} public void withdraw(int amount) { if (balance>amount) balance-=amount; } public void deposit(int amount) { balance+=amount; } }
class Current. Account : Bank. Account { private int overdraft. Facility; public Current. Account(int n, string name, int b, int ov) : base(n, name, b) { overdraft. Facility = ov; } public override void withdraw(int amount) { if (balance - amount > -overdraft. Facility) balance -= amount; } // balance is protected } class Deposit. Account : Bank. Account { private float interest. Rate; public Deposit. Account(int n, string name, int b, float rate) : base( n, name, b) { interest. Rate = rate; } float calc. Interest() { float interest = balance * interest. Rate; balance += (int)(interest); return interest; } }
Polymorphism and Object Oriented Programming Polymorphism is the key concept in object oriented programming n Polymorphism literally means many forms n Essentially we are able to get many different types of object behaviour from a single reference type u This enables us to write easily extensible applications n
Polymorphism and Object Oriented Programming n n For example in a computer game that simulates the movement of animals we can send ‘move’ commands to different types of animal We send the commands via an animal reference which is the base class for the different animal types u But each type behaves differently once it receives the command u Such an approach leads to a readily extendable application
Polymorphism and Object Oriented Programming Application animal Move
Polymorphism and Object Oriented Programming Polymorphism is implemented through references to objects n We can assign base class object references to any derived class object n Bank. Account acc 1 = new Current. Account(12345, "John Smith", 1000, 500); Bank. Account acc 2 = new Deposit. Account(54321, "Bill Jones", 2000, 5. 0);
Polymorphism and Object Oriented Programming Current. Account acc 1 12345 John Smith 1000 deposit() withdraw() 500 withdraw()
Polymorphism and Object Oriented Programming Deposit. Account acc 2 54321 Bill Jones 2000 deposit() withdraw() 5. 0 calc. Interest()
Polymorphism and Object Oriented Programming We can see that in the case of the reference to a Current. Account. Object object, method withdraw() is overidden in the derived class n The question is, which one is called at runtime? n public class Bank. Account. Test { static void Main(string[] args) { Bank. Account acc 1 = new Current. Account(12345, "John Smith“, 1000, 500); acc 1. withdraw(250); } } // Which withdraw()?
Polymorphism and Object Oriented Programming Current. Account acc 1 account. Number account. Holder balance deposit() withdraw() overdraft. Facility withdraw() Which one is called?
Polymorphism and Object Oriented Programming n n Clearly the behaviour of the object to the ‘withdraw’ message is important u The derived class behaviour takes into account the overdraft facility We must look at the definitions of the withdraw() method in the base and derived classes u The 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 Programming public class Bank. Account { //…… public virtual void withdraw(int amount) { if (balance - amount > -overdraft. Facility) balance -= amount; } } public class Current. Account : Bank. Account { private int overdraft. Facility; public Current. Account(n, name, b) {…} public override void withdraw(int amount) { if (balance - amount > -overdraft. Facility) balance -= amount; } }
Polymorphism and Object Oriented Programming n Because withdraw() in the derived class is declared as an override function of the virtual function in the base class, the correct behaviour is obtained public class Bank. Account. Test { static void Main(string[] args) { Bank. Account acc 1 = new Current. Account(12345, "John Smith“, 1000, 500); acc 1. withdraw(250); } } // Calls the Current. Account withdraw() method
Polymorphism and Object Oriented Programming n n n In Java, polymorphism (overriding the base class implementation) is the default behaviour In C++, the virtual keyword is used but no override keyword C# also has a keyword sealed for a base class method which can’t be overriden u Methods can also be declared override and sealed indicating that they override a base class method but can’t themselves be overriden
Abstract classes n In our example classes, the withdraw() method of our Bank. Account was declared as a virtual function u We were able to provide a sensible implementation of this function u This implementation could be regarded as default behaviour if the function was not overridden in derived classes
Abstract classes n If the method called can’t be resolved in the derived class, it is delegated back to the default base class method public class Bank. Account. Test { static void Main(string[] args) { Bank. Account acc 1 = new Current. Account(12345, "John Smith“, 1000, 500); acc 1. withdraw(250); // Calls the Current. Account withdraw() method Bank. Account acc 2 = new Deposit. Account(54321, “Bill Jones“, 2000, 5. 0); acc 2. withdraw(100); } } // Calls the Bank. Account withdraw() method
Abstract classes n Abstract classes arise when there is no sensible implementation of the virtual functions in the base class u n Base class virtual functions are always overridden by derived class implementations In this case, we simply declare the virtual function as abstract but provide no implementation u A class containing at least one abstract function must be declared an abstract class
Abstract classes n n As an example, suppose we wanted to design a hierarchy of shape classes for a computer graphics application Shape is an abstract concept u There is no sensible way we can implement functions to draw a shape or compute the area of a shape u It is natural to make such functions abstract u We can derive concrete classes from shape and provide implementations in the override functions
Abstract classes public 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 classes public 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; } }
Abstract classes n We can’t create Shape objects but we can declare Shape references and assign them to derived class objects using System; class Shape. Test { static void Main(string[] args) { Shape sq = new Square(10); Shape c = new Circle(5); System. Console. Write. Line("Area of square= " + sq. area()); System. Console. Write. Line("Area of circle= " + c. area()); } }
Generic programming n n Generic programming refers to performing operations on different types using a single piece of code u Examples include the application of searching and sorting algorithms to different data types In Java, this is done using polymorphism and the fact that all types are ultimately derived from a superclass object In C++ it is normally done using templates C# provides both mechanisms for generic programming u We will look at an example of generic searching using polymorphism
Generic programming n Suppose we want a generic search algorithm to search for any kind of object in an array n Class object provides an Equals() method to test whether one object is equal to another u u n Simply checks if the 2 object references point to the same area of memory Not very useful in practice We need to provide an Equals() method in the class of the object we are searching for u Polymorphism does the rest!
Generic Programming n In the following example we are searching for a Bank. Account object in an array u The search is based on the account number n Class Search. Alg provides a linear. Search method which carries out the search n We have provided an implementation of Equals() in class Bank. Account which overrides the Equals() method in object
public class { private Bank. Account int account. Number; string account. Holder; int balance; public Bank. Account(int n, string name , int b) { account. Number = n; account. Holder = name; balance = b; } public int Account. Number { // account. Number property} public string Account. Holder { // accoun. Holder 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) { Bank. Account b = (Bank. Account) obj; return (account. Number==b. account. Number); } }
Generic Programming using System; public class Search. Alg { public static int linear. Search(object[] a, object b) { int n=a. Length; for (int i=0; i<n; i++) { if (a[i]. Equals(b)) return i; } return -1; } }
Generic Programming using System; public class Bank. Account. Test { static void Main(string[] args) { Bank. Account[] b = new Bank. Account[3]; b[0]=new Bank. Account(12345, "John Smith", 100); b[1]=new Bank. Account(13579, "Bill Jones", 200); b[2]=new Bank. Account(87654, "Paul Brown", 300); Bank. Account bt=new Bank. Account(13579, "Jones. B", 700); int index=Search. Alg. linear. Search(b, bt); Console. Write. Line("Account found at index " + index); } }
Polymorphism and OOP n n Polymorphism is a key feature of object oriented programming Complex systems are able to be easily extended u The extendibility is provided by defining new classes within an inheritance hierarchy u Objects of these new classes are accessed through a base class reference u These objects add new behaviours to the system through a common interface to the application (the base class virtual functions)
Polymorphism and OOP n For example we could extend the list of animals to which we can send ‘move’ messages in our video game application u Each animal is responsible for its own movement code which can easily ‘plugin’ to the main application u Thus the application is easily extended with minimal changes to the main application code
Polymorphism and OOP animal Move . .
Summary n n We have looked at how we can extend existing classes through the idea of inheritance We have seen how, by accessing derived classes through a base class pointer, object behaviour is determined at run time through polymorphism We have looked at abstract classes where there is no obvious implementation of base class virtual methods u These methods are always overriden by derived class methods We have looked at the significance of polymorphism in object orientation u Object oriented applications are easily extended with additional code mainly confined to new derived classes
- Slides: 46