Write My Paper Button

WhatsApp Widget

Inheritance and Polymorphism in C# | My Assignment Tutor

Object Oriented ProgrammingInheritance andPolymorphism in C#Week 6Contents Base classes and derived classes Example – a BankAccount class Polymorphism and Object Oriented Programming Abstract classes Generic Programming Polymorphism and OOP SummaryBase classes and derived classes Inheritance is a fundamental requirement oforiented programming It allows us to create new classes by refiningexisting classes Essentially a derived class … Continue reading “Inheritance and Polymorphism in C# | My Assignment Tutor”

Object Oriented ProgrammingInheritance andPolymorphism in C#Week 6Contents Base classes and derived classes Example – a BankAccount class Polymorphism and Object Oriented Programming Abstract classes Generic Programming Polymorphism and OOP SummaryBase classes and derived classes Inheritance is a fundamental requirement oforiented programming It allows us to create new classes by refiningexisting classes Essentially a derived class can inherit datamembers of a base class The behaviour of the derived class can berefined by redefining base class memberfunctions or adding new member function A key aspect of this is polymorphism where aclasses behaviour can be adapted at run-timeBase classes and derived classes We can think of many examples in real life of howa (base) class can be refined to a set of (derived)classes For example a Polygon class can be refined to be aQuadrilateral which can be further refined to be aRectangle We can think of these classes as following an IS-Arelationship A Quadrilateral IS-A Polygon A Rectangle IS-A QuadrilateralBase classes and derived classes Base classDerived classShapeTriangle, Circle,RectangleBank AccountCurrent, DepositStudentUndergraduate,PostgaduateVehicleCar, Truck, BusFilterLow-pass, Band-pass,High-pass Example – a BankAccount class An BankAccount base class models basicinformation about a bank accountAccount holderAccount numberCurrent balance Basic functionalityWithdraw moneyDeposit moneypublic 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 AccountclassCurrentAccountCan have an overdraft facilityNo interest paidDepositAccountPays interest on any balanceNo overdraft facilityExample – a BankAccount class We will create our refined classes using inheritance fromthe BankAccount base class Classes CurrentAccount and DepositAccount inherit thebasic attributes (private members) of account accountNumber accountHolder balance Also, new attributes are added overdraftFacility interestRateExample – a BankAccount class In order to implement the derived classes, we need toconsider private/public access between base and derivedclasses public member functions of the base class becomepublic member functions of the derived class private members of the base class cannot be accessedfrom the derived class Obvious otherwise encapsulation could be easilybroken by inheriting from the base class Begs the question, how do we initialise derived classobjects?Example – a BankAccount class Base class methods and properties areaccessed through the base keywordbase(…..) refers to the base classconstructorbase.aMethod(…..) refers to a method ofthe base classbase.aProperty refers to a property of thebase classclass 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()CurrentAccount DepositAccountExample – a BankAccount class We can see that in both derived classes we need to accessthe balance instance field We can do this directly (without using a public method orproperty) by making balance a protected member of thebase class A protected class member is one that can be accessed bypublic member functions of the class as well as publicmember functions of any derived class Its half way between private and public Encapsulation is then broken for classes in theinheritance hierarchy and thus must be used whereperformance issues are criticalExample – a BankAccount class Class memberCan be accessed fromprivatepublic memberfunctions of same classprotectedpublic memberfunctions of same classand 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 protectedbalance -= 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 ObjectOriented Programming Polymorphism is the key concept in objectoriented programming Polymorphism literally means many forms Essentially we are able to get manydifferent types of object behaviour from asingle reference typeThis enables us to write easily extensibleapplicationsPolymorphism and ObjectOriented Programming For example in a computer game that simulatesthe movement of animals we can send ‘move’commands to different types of animal We send the commands via an animal referencewhich is the base class for the different animaltypes But each type behaves differently once itreceives the command Such an approach leads to a readily extendableapplicationPolymorphism and ObjectOriented Programminganimal Move ApplicationPolymorphism and ObjectOriented Programming Polymorphism is implemented throughreferences to objects We can assign base class object referencesto any derived class objectBankAccount acc1 = new CurrentAccount(12345, “John Smith”, 1000, 500);BankAccount acc2 = new DepositAccount(54321, “Bill Jones”, 2000, 5.0);Polymorphism and ObjectOriented Programmingacc1CurrentAccount 500withdraw() 12345John Smith1000deposit()withdraw()Polymorphism and ObjectOriented Programmingacc2DepositAccount 5.0calcInterest() 54321Bill Jones2000deposit()withdraw()Polymorphism and ObjectOriented Programming We can see that in the case of the referenceto a CurrentAccountObject object, methodwithdraw() is overidden in the derived class The question is, which one is called atruntime?public class BankAccountTest{static void Main(string[] args){BankAccount acc1 = new CurrentAccount(12345, “John Smith“,1000, 500);acc1.withdraw(250); // Which withdraw()?}}Polymorphism and ObjectOriented ProgrammingaccountNumberaccountHolderbalancedeposit()withdraw() overdraftFacilitywithdraw() acc1CurrentAccountWhich oneis called?Polymorphism and ObjectOriented Programming Clearly the behaviour of the object to the‘withdraw’ message is important The derived class behaviour takes into accountthe overdraft facility We must look at the definitions of the withdraw()method in the base and derived classes The base class withdraw() method is overriddenby the derived class method if the base classmethod is declared as virtual and the derivedclass method is declared as overridePolymorphism and ObjectOriented 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 ObjectOriented Programming Because withdraw() in the derived class isdeclared as an override function of the virtualfunction in the base class, the correct behaviour isobtainedpublic 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 ObjectOriented Programming In Java, polymorphism (overriding the base classimplementation) is the default behaviour In C++, the virtual keyword is used but nooverride keyword C# also has a keyword sealed for a base classmethod which can’t be overriden Methods can also be declared override andsealed indicating that they override a base classmethod but can’t themselves be overridenAbstract classes In our example classes, the withdraw()method of our BankAccount was declared asa virtual functionWe were able to provide a sensibleimplementation of this functionThis implementation could be regarded asdefault behaviour if the function was notoverridden in derived classesAbstract classespublic class BankAccountTest{static void Main(string[] args){BankAccount acc1 = new CurrentAccount(12345, “John Smith“,1000, 500);acc1.withdraw(250); // Calls the CurrentAccount withdraw() methodBankAccount 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 thederived class, it is delegated back to thedefault base class methodAbstract classes Abstract classes arise when there is no sensibleimplementation of the virtual functions in the baseclass Base class virtual functions are alwaysoverridden by derived class implementations In this case, we simply declare the virtual functionas abstract but provide no implementation A class containing at least one abstract functionmust be declared an abstract classAbstract classes As an example, suppose we wanted to design ahierarchy of shape classes for a computer graphicsapplication Shape is an abstract concept There is no sensible way we can implementfunctions to draw a shape or compute the areaof a shape It is natural to make such functions abstract We can derive concrete classes from shape andprovide implementations in the overridefunctionsAbstract 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 classes We can’t create Shape objects but we candeclare Shape references and assign them toderived 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());}}Generic programming Generic programming refers to performingoperations on different types using a single pieceof code Examples include the application of searchingand sorting algorithms to different data types In Java, this is done using polymorphism and thefact that all types are ultimately derived from asuperclass object In C++ it is normally done using templates C# provides both mechanisms for genericprogramming We will look at an example of genericsearching using polymorphismGeneric programming Suppose we want a generic search algorithm tosearch for any kind of object in an array Class object provides an Equals() method to testwhether one object is equal to another Simply checks if the 2 object references pointto the same area of memory Not very useful in practice We need to provide an Equals() method in theclass of the object we are searching for Polymorphism does the rest!Generic Programming In the following example we are searchingfor a BankAccount object in an arrayThe search is based on the accountnumber Class SearchAlg provides a linearSearchmethod which carries out the search We have provided an implementation ofEquals() in class BankAccount whichoverrides 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

CLAIM YOUR 30% OFF TODAY

X
Don`t copy text!
WeCreativez WhatsApp Support
Our customer support team is here to answer your questions. Ask us anything!
???? Hi, how can I help?