Download Inheritance and Polymorphism in C# and more Essays (high school) Computer science in PDF only on Docsity!
Object Oriented Programming
Inheritance and
Polymorphism in C#
Week 6
Contents
ļ® Base classes and derived classes
ļ® Example ā a BankAccount class
ļ® Polymorphism and Object Oriented Programming
ļ® Abstract classes
ļ® Generic Programming
ļ® Polymorphism and OOP
ļ® Summary
Base classes and derived classes
ļ® Inheritance is a fundamental requirement of
oriented programming
ļ® It allows us to create new classes by refining
existing classes
ļ® Essentially a derived class can inherit data
members of a base class
ļµ 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
ļ® 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
ļµ A Quadrilateral IS-A Polygon
ļµ A Rectangle IS-A Quadrilateral
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 class
ļ® We can consider refinements to our Account
class
ļµ CurrentAccount
ļ“ Can have an overdraft facility
ļ“ No interest paid
ļµ DepositAccount
ļ“ Pays interest on any balance
ļ“ No overdraft facility
Example ā a BankAccount class
ļ® We will create our refined classes using inheritance from
the BankAccount base class
ļ® Classes CurrentAccount and DepositAccount inherit the
basic attributes (private members) of account
ļµ accountNumber
ļµ accountHolder
ļµ balance
ļ® Also, new attributes are added
ļµ overdraftFacility
ļµ interestRate
Example ā a BankAccount class
ļ® In order to implement the derived classes, we need to
consider private/public access between base and derived
classes
ļµ 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
ļ“ Obvious otherwise encapsulation could be easily
broken by inheriting from the base class
ļ“ Begs the question, how do we initialise derived class
objects?
Example ā a BankAccount class
accountNumber accountHolder balance deposit() withdraw()
overdraftFacility
withdraw()
interestRate
calcInterest()
accountNumber accountHolder balance deposit() withdraw()
CurrentAccount DepositAccount
Example ā a BankAccount class
ļ® We can see that in both derived classes we need to access
the balance instance field
ļ® We can do this directly (without using a public method or
property) by making balance a protected member of the
base class
ļ® 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
ļµ 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 BankAccount class
Class member Can be accessed from
private public member
functions of same class
protected public member
functions of same class
and derived classes
public Anywhere
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;}
Polymorphism and Object
Oriented Programming
ļ® 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
ļµ But each type behaves differently once it
receives the command
ļµ Such an approach leads to a readily extendable
application
Polymorphism and Object
Oriented Programming
animal Move
Application
Polymorphism and Object
Oriented Programming
ļ® Polymorphism is implemented through
references to objects
ļ® We 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 Programming
acc
CurrentAccount
withdraw()
12345 John Smith 1000 deposit() withdraw()
Polymorphism and Object
Oriented Programming
accountNumber accountHolder balance deposit() withdraw()
overdraftFacility
withdraw()
acc
CurrentAccount
Which one
is called?
Polymorphism and Object
Oriented Programming
ļ® Clearly the behaviour of the object to the
ā withdrawā message is important
ļµ 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
ļµ 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 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 Programming
ļ® 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 BankAccountTest { static void Main(string[] args) { BankAccount acc1 = new CurrentAccount(12345, "John Smithā,1000, 500); acc1.withdraw(250); // Calls the CurrentAccount withdraw() method } }
Abstract classes
public 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 canāt be resolved in the
derived class, it is delegated back to the
default base class method
Abstract classes
ļ® Abstract classes arise when there is no sensible
implementation of the virtual functions in the base
class
ļµ 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
ļµ A class containing at least one abstract function
must be declared an abstract class
Abstract classes
ļ® As an example, suppose we wanted to design a
hierarchy of shape classes for a computer graphics
application
ļ® Shape is an abstract concept
ļµ There is no sensible way we can implement
functions to draw a shape or compute the area
of a shape
ļµ It is natural to make such functions abstract
ļµ 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;
Generic programming
ļ® Generic programming refers to performing
operations on different types using a single piece
of code
ļµ 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
ļµ We will look at an example of generic
searching using polymorphism
Generic programming
ļ® Suppose we want a generic search algorithm to
search for any kind of object in an array
ļ® Class object provides an Equals() method to test
whether one object is equal to another
ļµ 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
ļµ Polymorphism does the rest!
Generic Programming
ļ® In the following example we are searching
for a BankAccount object in an array
ļµ The search is based on the account
number
ļ® Class SearchAlg provides a linearSearch
method which carries out the search
ļ® We 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); } }