Presentation is loading. Please wait.

Presentation is loading. Please wait.

7/2/2015Assoc. Prof. Stoyan Bonev1 COS220 Concepts of PLs AUBG, COS dept Lecture 23 OOP Polymorphism Reference: R.Sebesta, Chapter 12 Lafore, Chapter 11.

Similar presentations


Presentation on theme: "7/2/2015Assoc. Prof. Stoyan Bonev1 COS220 Concepts of PLs AUBG, COS dept Lecture 23 OOP Polymorphism Reference: R.Sebesta, Chapter 12 Lafore, Chapter 11."— Presentation transcript:

1 7/2/2015Assoc. Prof. Stoyan Bonev1 COS220 Concepts of PLs AUBG, COS dept Lecture 23 OOP Polymorphism Reference: R.Sebesta, Chapter 12 Lafore, Chapter 11

2 7/2/2015Assoc. Prof. Stoyan Bonev2 Lecture Contents: Polymorphism illustrated Early binding and Late binding; –Regular member functions; –virtual member functions; –Methods accessed using pointers. Dynamic binding

3 7/2/2015Assoc. Prof. Stoyan Bonev3 The 3 main OOP characteristics Data Encapsulation/Data Hiding –Data and its member functions /methods/ are said to be encapsulated into a single entity. –Data is concealed within a class, so that it cannot be accessed mistakenly by functions outside the class. Inheritance Polymorphism

4 7/2/2015Assoc. Prof. Stoyan Bonev4 The 3 main OOP characteristics Data Encapsulation and Data Hiding Inheritance –The process of creating new classes, called derived classes from existing classes, called base classes Polymorphism

5 7/2/2015Assoc. Prof. Stoyan Bonev5 The 3 main OOP characteristics Data Encapsulation and Data Hiding Inheritance Polymorphism –Generally, the ability to appear in many forms –More specifically, in OOP it is the ability to redefine methods for derived classes –Giving different meanings to the same thing

6 7/2/2015Assoc. Prof. Stoyan Bonev6 Intro to Polymorphism Polymorphism means the Ability to process objects differently depending on their data type or class. Effectively, this means that you can ask many different objects to perform the same action.

7 7/2/2015Assoc. Prof. Stoyan Bonev7 Intro to Polymorphism Polymorphism Polymorphism means the ability to take more than one form. An operation may exhibit different behaviors in different instances. The behavior depends on the data types used in the operation. Polymorphism is extensively used in implementing Inheritance.

8 7/2/2015Assoc. Prof. Stoyan Bonev8 What is polymorphism? The concept of polymorphism (giving different meanings to the same thing). Early binding and Late binding. Regular /normal/ and virtual methods accessed via pointers. Examples: Base Derived1, Derived2 classes Person Professor, Student classes

9 7/2/2015Assoc. Prof. Stoyan Bonev9 What is polymorphism? Examples: Animal Mammal Cat Dog classes

10 7/2/2015Assoc. Prof. Stoyan Bonev10 Polymorphism Example: base class Shape, 3 derived classes Task: to draw a complicated image composed of 35 circles, 30 squares and 35 triangles (total number makes 100 primitive figures) using as less as possible statements (best to use one only statement) All classes have a method named void Draw(). The solution: Shape *ptr[100]; for (int I=0; I Draw(); or int I=0; while(I<=99) { (*ptr[I]).Draw(); I++; } Shape CircleSquareTriangle

11 7/2/2015Assoc. Prof. Stoyan Bonev11 Polymorphism-Python example1 Python makes extensive use of polymorphism in its basic types. For example, strings (immutable sequences of characters) and lists (mutable sequences of elements of any type) have the same indexing interface and the same lookup interface (which call the appropriate underlying methods). myString = 'Hello world' myList = [0, 'one', 1, 'two', 3, 'five', 8] print myString[:4] # prints Hell print myList[:4] # prints [0,'one',1,'two'] print 'e' in myString# prints True print 5 in myList# prints False

12 7/2/2015Assoc. Prof. Stoyan Bonev12 Polymorphism-Python example2 However, the most common examples of polymorphism are found in custom classes. Consider the very silly example, where two sub- classes ( Cat and Dog ) are derived from an Animal super-class. Two Cat objects and one Dog object are instantiated and given names, and then they are gathered in a list ([a, b, c]) and their talk method is called.

13 7/2/2015Assoc. Prof. Stoyan Bonev13 Polymorphism-Python example2 class Animal: def __init__(self, name): self.name = name class Cat(Animal): def talk(self): return 'Meow!' class Dog(Animal): def talk(self): return 'Arf! Arf!'

14 7/2/2015Assoc. Prof. Stoyan Bonev14 Polymorphism-Python example2 a = Cat('Missy') b = Cat(‘Pissy') c = Dog(‘Peter') for animal in [a, b, c]: print animal.name + ': ' + animal.talk() # prints the following: # # Missy: Meow! # Pissy: Meow! # Peter: Arf! Arf!

15 7/2/2015Assoc. Prof. Stoyan Bonev15 Polymorphism Example: base class Shape, 3 derived classes Task: to draw a complicated image composed of 35 circles, 30 squares and 35 triangles (totally 100 primitive figures) using as less as possible statements (best to use one only statement) All classes have a method named void Draw(). The solution: Shape *ptr[100]; for (int I=0; I Draw(); or int I=0; while(I<=99) { (*ptr[I]).Draw(); I++; } Shape CircleSquareTriangle

16 7/2/2015Assoc. Prof. Stoyan Bonev16 Reminder: what’s Polymorphism Giving different meanings to the same thing The same thing: the statement that calls method Draw() Different meaning: the effect of running method Draw() : drawing a specific primitive figure (a circle, or a square, or a triangle)

17 7/2/2015Assoc. Prof. Stoyan Bonev17 Polymorphism: requirements For the polymorphic approach to work, two requirements are to be valid: First, all the different classes of shapes, such as circles, squares, and triangles, must be derived from the same single base class (like super class Shape ). Second, the Draw() function must be declared to be virtual (a reserved word in C++) in the base class.

18 7/2/2015Assoc. Prof. Stoyan Bonev18 More details Polymorphism is provided by the dynamic binding of messages to method definitions. This is supported by allowing one to define variables of the type of the parent class ( Shape *ptr[100] ) that are also able to reference objects of any of the sub-classes (Circle, Square, Triangle) of the super-class (Shape). The parent class can define a method /like void Draw() / that is overridden by its sub-classes. When such a class is called through the base class reference variable, that call is dynamically bound to the method in the proper class.

19 7/2/2015Assoc. Prof. Stoyan Bonev19 More details (continued) In some cases the design of an inheritance hierarchy results in one or more classes that are so high in the hierarchy that an instantiation of them does not make sense. For example, probably it doesn’t make sense to have an implemented Draw() method in super Shape class. But because all of its descendant classes (Circle, Square, Triangle) should have such an implemented method, the protocol (but not the body) of that method is to be included in Shape class. This method is often called an abstract method (pure virtual method in C++). A class that includes at least one abstract method is called an abstract class (abstract base class in C++). Such a class cannot be instantiated because not all of its methods have bodies.

20 7/2/2015Assoc. Prof. Stoyan Bonev20 Member Functions accessed with pointers Introduction to virtual functions: Virtual means existing in appearance (effect) but not in reality. Early binding operates on regular /normal/ member functions (methods) accessed with pointers. Late binding operates on virtual member functions (methods) accessed with pointers.

21 7/2/2015Assoc. Prof. Stoyan Bonev21 Early binding / Late binding virtual vs. non virtual methods First example on Polymorphism: method Show() class Base {... }; class Derived1 : public Base {... }; class Derived2 : public Base {... }; Derived1 drv1;Derived2 drv2;Base *ptr; ptr = &drv1;ptr->Show(); ptr = &drv2;(*ptr).Show(); OOP3aEarlyBinding.cppOOP3aEarlyBinding.cpp OOP3aLateBinding.cppOOP3aLateBinding.cpp

22 7/2/2015Assoc. Prof. Stoyan Bonev22 Early Binding (at compile time) Normal, regular, non virtual methods class Base {public: void Show(){ cout << "\n Base:" ;}}; class Derived1 : public Base { public: void Show(){ cout << "\n Derived1:" ;} }; class Derived2 : public Base { public: void Show(){ cout << "\n Derived2:" ;} }; Major condition: the ptr pointer type – object of Base class Derived1 drv1;Derived2 drv2;Base *ptr; ptr = &drv1;ptr->Show(); ptr = &drv2;(*ptr).Show(); OOP3aEarlyBindig.cpp

23 7/2/2015Assoc. Prof. Stoyan Bonev23 Early Binding (at compile time) The compiler ignores the contents of the pointer ptr and selects the member function that matches the type of the pointer. See figure on next slide.

24 7/2/2015Assoc. Prof. Stoyan Bonev24 Early Binding (at compile time)

25 7/2/2015Assoc. Prof. Stoyan Bonev25 Late Binding (at run time) Virtual methods class Base {public: virtual void Show(){ cout << "\n Base:" ; } }; class Derived1 : public Base { public: void Show() { cout << "\n Derived1:" ;} }; class Derived2 : public Base { public: void Show() { cout << "\n Derived2:" ;} }; Major condition: the ptr pointer contents – object of derived class Derived1 drv1;Derived2 drv2;Base *ptr; ptr = &drv1;ptr->Show(); ptr = &drv2;(*ptr).Show(); OOP3aLateBinding.cpp

26 7/2/2015Assoc. Prof. Stoyan Bonev26 Late Binding (at run time) The compiler selects the function based on the contents of the pointer ptr, not on the type of the pointer. See figure on next slide.

27 7/2/2015Assoc. Prof. Stoyan Bonev27 Late Binding (at run time)

28 7/2/2015Assoc. Prof. Stoyan Bonev28 Late Binding (at run time) Pure virtual methods A virtual function with no body that is never executed. class Base { public: virtual void Show() = 0 ;}; class Derived1 : public Base { public: void Show(){ cout << "\n Derived1:" ;} }; class Derived2 : public Base { public: void Show(){ cout << "\n Derived2:" ;} };

29 29 More on OOP polymorphism Polymorphism in VBasic Polymorphism in C# Polymorphism in Java

30 30 VBasic: file oopPolymorphism.vb Class Base Public Overridable Sub Show() Console.WriteLine(" Base:") End Sub End Class Class Derived1 Inherits Base Public Overrides Sub Show() Console.WriteLine(" Derived1:") End Sub End Class Class Derived2 Inherits Base Public Overrides Sub Show() Console.WriteLine(" Derived2:") End Sub End Class Sub Main() Dim ptr As New Base() : ptr.Show() ptr = New Derived1() : ptr.Show() ptr = New Derived2() : ptr.Show() End Sub

31 31 C#, file oopPolymorphism.cs class Base { public virtual void Show() { Console.WriteLine( "\n Base:");} }; class Derived1 : Base { public override void Show() { Console.WriteLine( "\n Derived1:");} }; class Derived2 : Base { public override void Show() { Console.WriteLine( "\n Derived2:");} }; class Program { static void Main(string[] args) { Base ptr = new Base(); ptr.Show(); ptr = new Derived1(); ptr.Show(); ptr = new Derived2(); ptr.Show(); }

32 32 Java, file oopPolymorphism.java class Base { public void Show() { System.out.println( "\n Base:");} }; class Derived1 extends Base { public void Show() { System.out.println( "\n Derived1:");} }; class Derived2 extends Base { public void Show() { System.out.println( "\n Derived2:");} }; public class OOPPolymorhismJava { public static void main(String[] args) { Base ptr = new Base(); ptr.Show(); ptr = new Derived1(); ptr.Show(); ptr = new Derived2(); ptr.Show(); }

33 7/2/2015Assoc. Prof. Stoyan Bonev33 Early binding / Late binding virtual vs. non virtual methods Second example on Polymorphism: method isOutstanding() class Person {... }; class Professor: public Person {... }; class Student: public Person {... }; OOP3bIsOutstanding.cpp

34 7/2/2015Assoc. Prof. Stoyan Bonev34 Virtual method IsOutstanding() class Person { protected: string name; public: string getName() { return name; } void setName(string par) {name=par;} bool virtual isOutStanding() = 0; };

35 7/2/2015Assoc. Prof. Stoyan Bonev35 Virtual method IsOutstanding() class Student : public Person { private: float score; public: float getScore() { return score; } void setScore(float par) { score = par; } bool isOutStanding() { return (score > 98.0) ? true: false; } };

36 7/2/2015Assoc. Prof. Stoyan Bonev36 Virtual method IsOutstanding() class Professor : public Person { private: int NumPubs; public: int getNumPubs() { return NumPubs; } void setNumPubs(int par) { NumPubs = par; } bool isOutStanding() { return (NumPubs > 100) ? true: false; } };

37 7/2/2015Assoc. Prof. Stoyan Bonev37 Virtual method IsOutstanding() void main () { Person *PersPtr[100]; Student *StuPtr; Professor *ProPtr; int n=0; char choice; string nam; int papers; float scor; do { cout > choice; if (choice == 's') { StuPtr = new Student; cout > nam; StuPtr->setName(nam); cout > scor; StuPtr->setScore(scor); PersPtr[n++] = StuPtr; } else { ProPtr = new Professor; cout > nam; ProPtr->setName(nam); cout >papers; ProPtr->setNumPubs(papers); PersPtr[n++] = ProPtr; } cout > choice; } while (choice == 'y'); // end of do for (int j=0; j<n; j++) { cout getName(); if (PersPtr[j]->isOutStanding() == true) cout << " --outstanding person"; } // end of for }// end of main()

38 7/2/2015Assoc. Prof. Stoyan Bonev38 Early binding / Late binding virtual vs. non virtual methods Second example on Polymorphism: method isOutstanding() class Person {... }; class Professor: public Person {... }; class Student: public Person {... }; OOP3b.cppOOP3b.exeOOP3b.cppOOP3b.exe

39 Polymorphism in C++ Conclusion

40 7/2/2015Assoc. Prof. Stoyan Bonev40 Polymorphism in C++ classified Dynamic polymorphism – present lecture –Based on late binding and virtual methods Static or ad-hoc polymorphism – lecture on the subroutine concept –Based on overloaded functions concept Parametric (generic) polymorphism – lecture on generic programming –Based oh template reserved word

41 Another aspect of usage for reserved word virtual

42 7/2/2015Assoc. Prof. Stoyan Bonev42 Virtual Base classes Reminder: Diamond inheritance A special type of naming conflict is introduced if a class D multiply inherits from super classes B and C which themselves are derived from one super class A. This leads to an inheritance graph as shown in Figure

43 7/2/2015Assoc. Prof. Stoyan Bonev43 Virtual Base classes A – class Parent B – class Child1C – class Child2 D – class Grandchild A problem arises if a method in D class wants to access data or method in A.

44 7/2/2015Assoc. Prof. Stoyan Bonev44 Virtual Base classes class Parent {protected: int basedata; }; class Child1 : public Parent { } ; class Child2 : public Parent { } ; class Grandchild: public Child1, public Child2 { public: int getdata() { return basedata; } // error: ambiguity }; Child1 inherits copy of Parent’s basedata. Child2 inherits copy of Parent’s basedata. Which basedata does Grandchild inherit?

45 7/2/2015Assoc. Prof. Stoyan Bonev45 Virtual classes – resolving ambiguity class Parent {protected: int basedata; }; class Child1 : virtual public Parent { } ; class Child2 : virtual public Parent { } ; class Grandchild:public Child1,public Child2 { public: int getdata() { return basedata; } // no error }; The use of virtual reserved word in both classes Child1, Child2 causes them to share a single common sub-object of their base class Parent. So, since there is only one copy of basedata, there is no ambiguity and it is referred to in sub-sub-class Grandchild

46 7/2/2015Assoc. Prof. Stoyan Bonev46 Exercise OOP. Polymorphism. Coming slides include problem tasks to be solved at the OOP practical session.

47 7/2/2015Assoc. Prof. Stoyan Bonev47 Exercise OOP. Polymorphism. Test all programs discussed in the lecture. Build program illustrating polymorphism. Animal Mammal Cat Dog classes and method talk() Demo program SBPolymorphism3.cpp

48 7/2/2015Assoc. Prof. Stoyan Bonev48 Demos oop3aEarlyBinding.cpp, oop3aLateBiding.cpp, oop3bIsOutStanding.cpp.

49 7/2/2015Assoc. Prof. Stoyan Bonev49 Tasks Task 1. Test the early binding effect and late binding effect using pointers to call method Show() in the Base, Derived1 and Derived2 classes presented in the lecture.

50 ISBN 0-321-49362-1 Chapter 12 Support for Object-Oriented Programming

51 Copyright © 2009 Addison-Wesley. All rights reserved.1-51Copyright © 2009 Addison-Wesley. All rights reserved.1-51 Dynamic Binding A polymorphic variable can be defined in a class that is able to reference (or point to) objects of the class and objects of any of its descendants When a class hierarchy includes classes that override methods and such methods are called through a polymorphic variable, the binding to the correct method will be dynamic Allows software systems to be more easily extended during both development and maintenance

52 Copyright © 2009 Addison-Wesley. All rights reserved.1-52Copyright © 2009 Addison-Wesley. All rights reserved.1-52 Dynamic Binding Concepts An abstract method is one that does not include a definition (it only defines a protocol) An abstract class is one that includes at least one virtual method An abstract class cannot be instantiated

53 Copyright © 2009 Addison-Wesley. All rights reserved.1-53Copyright © 2009 Addison-Wesley. All rights reserved.1-53 Type Checking and Polymorphism Polymorphism may require dynamic type checking of parameters and the return value –Dynamic type checking is costly and delays error detection If overriding methods are restricted to having the same parameter types and return type, the checking can be static

54 Copyright © 2009 Addison-Wesley. All rights reserved.1-54Copyright © 2009 Addison-Wesley. All rights reserved.1-54 Dynamic and Static Binding Should all binding of messages to methods be dynamic? –If none are, you lose the advantages of dynamic binding –If all are, it is inefficient Allow the user to specify

55 Thank You For Your Attention


Download ppt "7/2/2015Assoc. Prof. Stoyan Bonev1 COS220 Concepts of PLs AUBG, COS dept Lecture 23 OOP Polymorphism Reference: R.Sebesta, Chapter 12 Lafore, Chapter 11."

Similar presentations


Ads by Google