[go: up one dir, main page]

0% found this document useful (0 votes)
4 views40 pages

Lecture 8 Polymorphism

Polymorphism in programming allows methods with the same name to behave differently based on the object invoking them, enabling flexibility and extensibility in code. In C++, it is primarily implemented through virtual methods and can be categorized into various types such as ad-hoc, universal, coercion, and parametric polymorphism. Abstract classes in C++ and Java further enhance polymorphism by defining common interfaces for subclasses, which must implement abstract methods.

Uploaded by

Harry Supa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views40 pages

Lecture 8 Polymorphism

Polymorphism in programming allows methods with the same name to behave differently based on the object invoking them, enabling flexibility and extensibility in code. In C++, it is primarily implemented through virtual methods and can be categorized into various types such as ad-hoc, universal, coercion, and parametric polymorphism. Abstract classes in C++ and Java further enhance polymorphism by defining common interfaces for subclasses, which must implement abstract methods.

Uploaded by

Harry Supa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

1

Polymorphism
Polymorphism
2

 Polymorphism refers to the ability to determine at


runtime which code to run, given multiple
methods with the same name but different
operations in the same class or in different classes
 In C++, polymorphism is also referred to as
called overloading.
 Typically, when the term polymorphism is used
with C++, however, it refers to using virtual
methods, which we'll discuss shortly.
Polymorphism
3

 When a program invokes a method through a


superclass variable,
 the correct subclass version of the method is
called,
 based on the type of the reference stored in the
superclass variable
 The same method name and signature can cause
different actions to occur,
 depending on the type of object on which the
method is invoked
Polymorphism
4

 Polymorphism enables programmers to deal in


generalities and
 let the execution-time environment handle the
specifics.
 Programmers can command objects to behave in
manners appropriate to those objects,
 without knowing the types of the objects

 (as long as the objects belong to the same


inheritance hierarchy).
Polymorphism Promotes Extensibility
5

 Software that invokes polymorphic behavior


 independent of the object types to which
messages are sent.
 New object types that can respond to existing
method calls can be
 incorporated into a system without requiring
modification of the base system.
 Only client code that instantiates new objects
must be modified to accommodate new types.
Types of Polymorphism

Polymorphism

Ad hoc Universal

Coercion Overloading Subtyping Genericity


(Inclusion) (Parametric)

Code Entities

Inclusion, or subtype polymorphism arises from inheritance.


Types of Polymorphism
7

 In universal polymorphism, the same code applies


to different types. I.e. polymorphic function use a
single algorithm independent of the type of its
arguments
 In ad-hoc polymorphism, different code may be
executed for different types. I.e. different
operations on different types known by the same
name e.g. overloading
Types of Polymorphism
8

 Overloading means that functions of the same name may be


implemented differently for different types.
 Also the user or system overloads an identifier or operator
to work with different types
 add(char a, char b, double x, double y)
 {
a + b; x + y; /*verloading of +
operator. */
 }
 //overloading of the function name max:
 double max(double d1, double d2);
 char max(char c1, char c2);
Types of Polymorphism
9

 Coercion is the automatic application of built-in or


user-defined type conversions. E.g. when adding an
integral and a floating point number the integral
number is promoted automatically to a floating point
number by the compiler.
 int pi = 3.14159; // Built-in conversion
from double to int
float x = '\0'; // Built-in coercion from
char to float
extern double sqrt(double);
 x = (double)sqrt(pi); // coercion from int
to double and then
Types of Polymorphism
10

 Overloading and coercion may conflict if an


appropriate conversion and an overloaded function
are available at the same time.
 Parametric Polymorphism: a polymorphic function has
an implicit or explicit type parameter which determines
the type of the argument for each application of that
function. E.g. geNumber (int num), or geNumber (char
*num),
 Inclusion Polymorphism: an object can be viewed as
belonging to many different classes that need not be
disjoint/separate; that is, there may be inclusion of
classes. E.g. Dog, Bird belongs to Animal
Polymorphism in C++ Pointers to Classes
11

 A class is an expanded concept of a data structure:


instead of holding only data, it can hold both data
and functions.

 An object is an instantiation of a class. In terms of


variables, a class would be the type, and an object
would be the variable.

 A pointer is simply a data variable containing the


address of an actual data value.
Polymorphism in C++ Pointers to Classes
12

 We can create pointers that point to classes.


 Once declared, a class becomes a valid type, so we can
use the class name as the type for the pointer. E.g. if
we have a class called Rectangle:
 CRectangle * prect; is a pointer to an object of class
CRectangle.

 In order to refer directly to a member of an object


pointed by a pointer we can use the arrow operator
(->) of indirection.
 Following is an example with some possible
combinations:
Polymorphism in C++ Pointers to Classes
13

// pointer to classes example


#include <iostream>
using namespace std;
class CRectangle
{
int width, height;
public:
void set_values (int, int);
int area (void)
{
return (width * height);}
};
Polymorphism in C++ Pointers to Classes
14
void CRectangle::set_values (int a, int b)
{
width = a; height = b;
}
int main () {
CRectangle a, *b, *c;
CRectangle * d = new CRectangle[2];
b= new CRectangle; c= &a;
a.set_values (1,2);
b->set_values (3,4);
d->set_values (5,6);
Polymorphism in C++ Pointers to Classes
15

d[1].set_values (7,8);
cout << "a area: " << a.area() << endl;
cout << "*b area: " << b->area() << endl;
cout << "*c area: " << c->area() << endl;
cout << "d[0] area: " << d[0].area()<< endl;
cout << "d[1] area: " << d[1].area()<< endl;
delete[] d;
delete b;
return 0;
}
Polymorphism in C++ Pointers to Classes
16

expression can be read as


*x pointed by x
&x address of x
x.y member y of object x
x- >y member y of object pointed by x
(*x).y member y of object pointed by x (equivalent to the previous one)
x[0] first object pointed by x
x[1] second object pointed by x
x[n] (n+1)th object pointed by x
Polymorphism in C++ Pointers to Classes
17

 A pointer to a derived class is type-compatible with


a pointer to its base class.

 Polymorphism is the art of taking advantage of this


simple but powerful and versatile/flexible feature,
that brings Object Oriented Methodologies to its full
potential.

 Lets re-write our polygon program taking into


consideration the pointer compatibility
Polymorphism
18

//pointers to base class


#include <iostream>
using namespace std;
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{
width=a; height=b; }
};
Polymorphism
19

class CRectangle: public CPolygon


{
public:
int area () { return (width * height); }
};
class CTriangle: public CPolygon {
public:
int area () { return (width * height / 2);
}
};
Polymorphism
20

NB
int main () {
CRectangle rect; - We use pointers of type base class to

CTriangle trgl; refer to the members that CRectangle

CPolygon * ppoly1 = &rect; and CTriangle inherit from CPolygon.


CPolygon * ppoly2 = &trgl; - Since *ppoly1 and *ppoly2 are of type
ppoly1->set_values (4,5); Cpolygon, when we call the area()
ppoly2->set_values (4,5); members at the end of the program we
cout << rect.area() << endl; have had to use directly the objects
cout << trgl.area() << endl; rect and trgl instead of the pointers
return 0; *ppoly1 and *ppoly2.
}
Polymorphism in C++ Pointers to Classes
21

 In order to use area() with the pointers to class


CPolygon, this member should also have been
declared in the class CPolygon, and not only in its
derived classes,
 but the problem is that CRectangle and CTriangle
implement different versions of area, therefore we
cannot implement it in the base class.
 A member of a class that can be redefined in its
derived classes is known as a virtual member. In
order to declare a member of a class as virtual, we
must precede its declaration with the keyword
virtual
Polymorphism in C++ Virtual members
22

// virtual members
#include <iostream>
using namespace std;
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area () { return (0); }
};
class CRectangle: public CPolygon {
public:
int area () { return (width * height); }
};
Polymorphism in C++ Virtual members
23

class CTriangle: public CPolygon {


public:
int area () { return (width * height /
2); }
};
int main () {
CRectangle rect;
CTriangle trgl;
CPolygon poly;
CPolygon * ppoly1 = &rect;
CPolygon * ppoly2 = &trgl;
Polymorphism in C++ Virtual members
24

CPolygon * ppoly3 = &poly;


ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
ppoly3->set_values (4,5);
cout << ppoly1->area() << endl;
cout << ppoly2->area() << endl;
cout << ppoly3->area() << endl;
return 0;
}
Polymorphism in C++ Virtual members
25

 The member function area() has been declared as virtual in


the base class because it is later redefined in each derived
class.

 The virtual keyword allows a member of a derived class with


the same name as one in the base class to be appropriately
called from a pointer, and more precisely when the type of
the pointer is a pointer to the base class but is pointing to an
object of the derived class, as in the above example.

 A class that declares or inherits a virtual function is called a


polymorphic class.
Polymorphism - Abstract Classes
26

 Abstract classes
 Are superclasses (called abstract superclasses)
 Cannot be instantiated
 Incomplete
 subclasses fill in "missing pieces"

Note:
 Concrete classes
 Can be instantiated
 Implement every method they declare
 Provide specifics
Polymorphism - Abstract Classes
27

 Declares common attributes and behaviors of the


various classes in a class hierarchy.
 Typically contains one or more abstract methods
 Subclasses must override if the subclasses are to be concrete.
 Instance variables and concrete methods of an
abstract class subject to the normal rules of
inheritance.
Polymorphism - Abstract Classes
28

 Purpose of an abstract class


 Declare common attributes …
 Declare common behaviors of classes in a class
hierarchy
 Contains one or more abstract methods
 Subclasses must override

 Instance variables, concrete methods of abstract class


 subject to normal rules of inheritance
Polymorphism - Abstract base classes

 Circle and Rectangle are concrete classes with their own


separate implementations of the methods area() and
Perimeter()
Shape
Shape is an abstract class with
area() no implementation of area()
perimeter() and perimeter()

Rectangle
Circle
area()
area()
perimeter()
perimeter()
Polymorphism in C++ - Abstract base classes
30

 Using our previous example, in an abstract base classes we


could leave area() member function without implementation.
This is done by appending =0 (equal to zero) to the function
declaration.
 An abstract base CPolygon class could look like as follows:
// abstract class CPolygon
class CPolygon { This type of function is called a
protected: pure virtual function, and all
int width, height; classes that contain at least
public: one pure virtual function are
void set_values (int a, int b) abstract base classes.
{ width=a; height=b; }
virtual int area () =0;
};
Polymorphism - Abstract base classes
31

 In abstract base classes we cannot create instances


(objects) of it if at least one of its members lacks
implementation
 But a class that cannot instantiate objects is not totally
useless; We can create pointers to it and take
advantage of all its polymorphic abilities.
 Beware! Compile Time Errors
 Attempting to instantiate an object of an abstract class

 Failure to implement a superclass’s abstract methods


in a subclass
Polymorphism in C++ - Abstract base classes
32

// abstract base class


#include <iostream>
using namespace std;
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area (void) =0;
};
Polymorphism in C++ - Abstract base classes
33

class CRectangle: public CPolygon {


public:
int area (void)
{
return (width * height); }
};
class CTriangle: public CPolygon
{
public:
int area (void)
{
return (width * height / 2); }
};
Polymorphism in C++ - Abstract base classes
34

int main () {
CRectangle rect;
CTriangle trgl;
CPolygon * ppoly1 = &rect;
CPolygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
cout << ppoly1->area() << endl;
cout << ppoly2->area() << endl;
return 0;
}
Polymorphism in Java - Abstract Classes
35

 Use to declare a class abstract


 Also use to declare a method abstract
 Abstract classes normally contain one or more
abstract methods
 All concrete subclasses must override all inherited
abstract methods
 Iterator class
 Traverses all the objects in a collection, such as an array
 Often used in polymorphic programming to traverse a
collection that contains references to objects from
various levels of a hierarchy
Polymorphism in Java - Abstract Classes
public abstract class Shape {
protected String shapeName;
public Shape(String name)
{shapeName = name;}
public abstract double area ();
public abstract double perimeter();
public String toString()
{
return shapeName;
};
}

Class MUST be qualified as abstract if one or more methods are abstract


There can be NO instances of an abstract class (no Shape objects)
Polymorphism in Java - Abstract Classes
37
public class Rectangle extends Shape
{
protected double length, width;
public Rectangle(double len, double wid)
{
super(“Rectangle”);
length = len; width = wid;
}
public double area ()
{
return length * width;}
public double perimeter ( ) {
return 2.0 * (length + width); }
}
Polymorphism in Java - Abstract Classes
38
public class Circle extends Shape {
private double radius;
public Circle (double rad)
{
super (“Circle”);
radius = rad;
}
public double area( )
{
return Math.PI * radius * radius; }
public double perimeter( ) {
return 2.0 * Math.PI * radius; }
}
Polymorphism in Java - Abstract Classes
39

package javapolymorphism;
public class MainApplication {
public static void main (String [] args)
{
CircleSubClass MyCircle = new
CircleSubClass(3.0);
RectangleSuClass MyRectangle = new
RectangleSuClass(4.0,5.0);
System.out.printf("The area of the circle
is %.3f\n",MyCircle.area( ));
Polymorphism in Java - Abstract Classes
40

System.out.printf("The perimeter of the


circle is %.3f\n",
MyCircle.perimeter());
System.out.printf("The area of rectangle
is %.3f\n",MyRectangle.area( ));
System.out.printf("The perimeter of the
rectangle is %.3f\n",
MyRectangle.perimeter());
}
}

You might also like