Presentation is loading. Please wait.

Presentation is loading. Please wait.

Inheritance and Polymorphism Lecture 3. C# Classes  Classes are used to accomplish:  Modularity: Scope for methods  Blueprints for generating objects.

Similar presentations


Presentation on theme: "Inheritance and Polymorphism Lecture 3. C# Classes  Classes are used to accomplish:  Modularity: Scope for methods  Blueprints for generating objects."— Presentation transcript:

1 Inheritance and Polymorphism Lecture 3

2 C# Classes  Classes are used to accomplish:  Modularity: Scope for methods  Blueprints for generating objects or instances:  Per instance data and method signatures  Classes support  Data encapsulation - private data and implementation.  Inheritance - code reuse

3 Inheritance  Inheritance allows a software developer to derive a new class from an existing one.  The existing class is called the parent, super, or base class.  The derived class is called a child or subclass.  The child inherits characteristics of the parent.  Methods and data defined for the parent class.  The child has special rights to the parents methods and data.  Public access like any one else  Protected access available only to child classes (and their descendants).  The child has its own unique behaviors and data.

4 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

5 Inheritance  Inheritance relationships are often shown graphically in a class diagram, with the arrow pointing to the parent class.  Inheritance should create an is-a relationship, meaning the child is a more specific version of the parent. Animal Bird

6 Examples: Base Classes and Derived Classes

7 Declaring a Derived Class  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class contents }

8 Example – a BankAccount class  A BankAccount base class models basic information about a bank account  Account holder  Account number  Current balance  Basic functionality  Withdraw money  Deposit money

9 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 { return accountNumber;} public string AccountHolder { return accounHolder;} public int Balance { return balance; } public void withdraw(int amount) { if (balance>amount) balance-=amount; } public void deposit(int amount) { balance+=amount;} }

10 Example – a BankAccount class  We can consider refinements to our Account class  CurrentAccount (vadesiz hesap)  Can have an overdraft facility  No interest paid  DepositAccount (vadeli hesap)  Pays interest on any balance  No overdraft facility

11 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

12 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  Brings the question, how do we initialise derived class objects?

13 Example – a BankAccount class  Base class methods and properties are accessed through the base keyword  base(.....) refers to the base class constructor  base.aMethod(.....) refers to a method of the base class  base.aProperty refers to a property of the base class

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

15 Example – a BankAccount class accountNumber accountHolder balance deposit() withdraw() overdraftFacility withdraw() interestRate calcInterest() accountNumber accountHolder balance deposit() withdraw() CurrentAccountDepositAccount

16 Controlling Inheritance  A child class inherits the methods and data defined for the parent class; however, whether a data or method member of a parent class is accessible in the child class depends on the visibility modifier of a member.  Variables and methods declared with private visibility are not accessible in the child class  However, a private data member defined in the parent class is still part of the state of a derived class.  Variables and methods declared with public visibility are accessible; but public variables violate our goal of encapsulation  There is a third visibility modifier that helps in inheritance situations: protected.

17 The protected Modifier  Variables and methods declared with protected visibility in a parent class are only accessible by a child class or any class derived from that class + public - private # protected Book # pages : int + GetNumberOfPages() : void Dictionary - definition : int + PrintDefinitionMessage() : void

18 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 only the classes in the inheritance hierarchy

19 Example – a BankAccount class Class memberCan be accessed from privatepublic member functions of same class protectedpublic member functions of same class and derived classes publicAnywhere

20 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 { return accountNumber;} public string AccountHolder { return accounHolder;} public int Balance { return balance; } public void withdraw(int amount) { if (balance>amount) balance-=amount; } public void deposit(int amount) { balance+=amount;} }

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

22 Single Inheritance  Some languages, e.g., C++, allow Multiple inheritance, which allows a class to be derived from two or more classes, inheriting the members of all parents.  C# and Java support single inheritance, meaning that a derived class can have only one parent class.

23 Class Hierarchies  A child class of one parent can be the parent of another child, forming a class hierarchy Animal ReptileBirdMammal SnakeLizardBatHorseParrot

24 Class Hierarchies CommunityMember EmployeeStudentAlumnus FacultyStaff ProfessorInstructor GraduateUnder

25 Class Hierarchies Shape TwoDimensionalShapeThreeDimensionalShape SphereCubeCylinderTriangleSquareCircle

26 Class Hierarchies  An inherited member is continually passed down the line  Inheritance is transitive.  Good class design puts all common features as high in the hierarchy as is reasonable. Avoids redundant code.

27 Polymorphism and Object Oriented Programming  Polymorphism is the key concept in object oriented programming  Polymorphism literally means many forms  Essentially we are able to get many different types of object behaviour from a single reference type  This enables us to write easily extensible applications

28 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

29 Polymorphism and Object Oriented Programming animal Move Application

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

31 Polymorphism and Object Oriented Programming acc1 CurrentAccount 500 withdraw() 12345 John Smith 1000 deposit() withdraw()

32 Polymorphism and Object Oriented Programming acc2 DepositAccount 5.0 calcInterest() 54321 Bill Jones 2000 deposit() withdraw()

33 Overriding Methods  A child class can override the definition of an inherited method in favor of its own  That is, a child can redefine a method that it inherits from its parent  The new method must have the same signature as the parent's method, but can have a different implementation.  The type of the object executing the method determines which version of the method is invoked.  CurrentAccount overrides withdraw function of BankAccount

34 Polymorphism and Object Oriented Programming  We can see that in the case of the reference to a CurrentAccountObject object, method withdraw() is overidden in the derived class  The 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()? }

35 Polymorphism and Object Oriented Programming accountNumber accountHolder balance deposit() withdraw() overdraftFacility withdraw() acc1 CurrentAccount Which one is called?

36 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

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

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

39 Polymorphism and Object Oriented Programming  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  Methods can also be declared override and sealed indicating that they override a base class method but can’t themselves be overriden

40 sealed  If an instance method declaration includes the sealed modifier, it must also include the override modifier.  Use of the sealed modifier prevents a derived class from further overriding the method.

41 Dynamic Binding  A polymorphic reference is one which can refer to different types of objects at different times. It morphs!  The type of the actual instance, not the declared type, determines which method is invoked.  Polymorphic references are therefore resolved at run-time, not during compilation.  This is called dynamic binding.

42 Overriding Methods  C# requires that all class definitions communicate clearly their intentions.  The keywords virtual, override and sealed provide this communication.  If a base class method is going to be overridden it should be declared virtual.  A derived class would then indicate that it indeed does override the method with the override keyword.

43 Overloading vs. Overriding  Overloading deals with multiple methods in the same class with the same name but different signatures  Overloading lets you define a similar operation in different ways for different data  Example: int foo(string[] bar); int foo(int bar1, float a);  Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature  Overriding lets you define a similar operation in different ways for different object types  Example: class Base { public virtual int foo() {} } class Derived { public override int foo() {}}

44 Type Unification  Everything in C# inherits from object  Similar to Java except includes value types.  Value types are still light-weight and handled specially by the CLI(Common Language Infrastructure) /CLR (Common Language Runtime).  This provides a single base type for all instances of all types.  Called Type Unification

45 The System.Object Class  All classes in C# are derived from the Object class  if a class is not explicitly defined to be the child of an existing class, it is a direct descendant of the Object class  The Object class is therefore the ultimate root of all class hierarchies.  The Object class defines methods that will be shared by all objects in C#, e.g.,  ToString: converts an object to a string representation  Equals: checks if two objects are the same  GetType: returns the type of a type of object  A class can override a method defined in Object to have a different behavior, e.g.,  String class overrides the Equals method to compare the content of two strings

46 Abstract classes  In our example classes, the withdraw() method of our BankAccount was declared as a virtual function  We were able to provide a sensible implementation of this function  This implementation could be regarded as default behaviour if the function was not overridden in derived classes

47 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

48 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

49 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

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

51 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*radius;} }

52 Abstract classes  We can’t create Shape objects but we can declare Shape references and assign them to derived class objects using 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()); }

53 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

54 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!

55 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

56 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) //existing virtual method { BankAccount b = (BankAccount) obj; return (accountNumber==b.accountNumber); }

57 Generic Programming using System; public class SearchAlg { public static int linearSearch(object[] a, object b) { int n=a.Length; for (int i=0; i<n; i++) { if (a[i].Equals(b)) return i; } return -1; }

58 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("Account found at index " + index); } Generic Programming


Download ppt "Inheritance and Polymorphism Lecture 3. C# Classes  Classes are used to accomplish:  Modularity: Scope for methods  Blueprints for generating objects."

Similar presentations


Ads by Google