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.

Slides:



Advertisements
Similar presentations
Object-Oriented Programming Session 9 Course : T Programming Language Concept Year : February 2011.
Advertisements

Object Oriented Programming
Overriding CMPS Overriding Recall, a method in a child class overrides a method in the parent class, if it has the same name and type signature.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
4/14/2015Assoc. Prof. Stoyan Bonev1 COS220 Concepts of PLs AUBG, COS dept Lecture 23m2 OOP Friend Functions Ref: Sebesta, Chapter 12; Lafore, Chapter 11.
Inheritance. Many objects have a hierarchical relationship –Examples: zoo, car/vehicle, card game, airline reservation system Inheritance allows software.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 15: Polymorphism,
Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University.
Inheritance, Polymorphism, and Virtual Functions
Inheritance and Polymorphism CS351 – Programming Paradigms.
Virtual Functions Junaed Sattar November 10, 2008 Lecture 10.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Polymorphism &Virtual Functions
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Object-oriented programming: C++ class A { private: …… // can be accessd by A protected: …… // can be accessed by A and // its derived classes public:
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Chapter 12 Object Oriented Design.  Complements top-down design  Data-centered view of design  Reliable  Cost-effective.
Chapter 12 Support for Object oriented Programming.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Inheritance, Polymorphism, And Virtual Functions Chapter 15.
What Is Inheritance? Provides a way to create a new class from an existing class New class can replace or extend functionality of existing class Can be.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
Chapter 12 Support for Object-Oriented Programming.
Object-Oriented Programming Chapter Chapter
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
ISBN Object-Oriented Programming Chapter Chapter
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Chapter -6 Polymorphism
Coming up: Inheritance
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
CMSC 202 Polymorphism. 10/20102 Topics Binding (early and late) Upcasting and downcasting Extensibility The final modifier with  methods  classes.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Testing in OO Environment The reasons for testing is not any different for any of the design and implementation methodologies, including OO methodology.
3/20/2016Assoc. Prof. Stoyan Bonev1 COS220 Concepts of PLs AUBG, COS dept Lecture 23 OOP Polymorphism Reference: R.Sebesta, Chapter 12 Lafore, Chapter.
 Virtual Function Concepts: Abstract Classes & Pure Virtual Functions, Virtual Base classes, Friend functions, Static Functions, Assignment & copy initialization,
CSCI-383 Object-Oriented Programming & Design Lecture 17.
ISBN Chapter 12 Support for Object-Oriented Programming.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
Inheritance, Polymorphism, and Virtual Functions
Polymorphism.
ATS Application Programming: Java Programming
Object Oriented Analysis and Design
Java Programming Language
Virtual Functions Department of CSE, BUET Chapter 10.
Inheritance, Polymorphism, and Virtual Functions
Week 6 Object-Oriented Programming (2): Polymorphism
Polymorphism CMSC 202, Version 4/02.
Support for Object-Oriented Programming
CISC/CMPE320 - Prof. McLeod
Chapter 9 Carrano Chapter 10 Small Java
Overview of C++ Polymorphism
Java Programming: From the Ground Up
Lecture 10 Concepts of Programming Languages
Topics OOP Review Inheritance Review Abstract Classes
Static Binding Static binding chooses the function in the class of the base class pointer, ignoring any versions in the class of the object actually.
Programming in C# CHAPTER 5 & 6
Presentation transcript:

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

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

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

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

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

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/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.

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

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

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

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

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.

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

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!

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

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)

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.

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.

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.

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.

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

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

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.

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

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

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.

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

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 More on OOP polymorphism Polymorphism in VBasic Polymorphism in C# Polymorphism in Java

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 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 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(); }

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

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

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

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

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()

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

Polymorphism in C++ Conclusion

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

Another aspect of usage for reserved word virtual

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

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.

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?

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

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

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

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

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.

ISBN Chapter 12 Support for Object-Oriented Programming

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

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

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

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

Thank You For Your Attention