1. Polymorphism
Poly → many
Morph → shapes (“behaviors”)
Copyright 2008 -- Walter Wesley 1
2. Advanced Polymorphism
• You should already have a basic
understanding of polymorphism.
• But do you really understand how
polymorphism works?
• How does the compiler actually implement
polymorphism?
Copyright 2008 -- Walter Wesley 2
3. Polymorphism in C++
• Suppose you have a C++ class. It has a
few methods, and some instance variables
(fields).
• In your program, you instantiate an object
and you get and display the size in bytes of
the object (C++ has a sizeof operator that
provides the size of its operand).
• You record the number of bytes.
Copyright 2008 -- Walter Wesley 3
• You now change your class by placing the
4. Polymorphism in C++
(continued)
• Even though all you did was introduce the “virtual”
keyword (in C++ the virtual keyword is used to
specify that you want that method to behave
polymorphically), your object has increased in size by
4 bytes.
• It is as if a pointer has been added to your object (4
bytes is exactly the size of a pointer instance
variable).
Copyright 2008 -- Walter Wesley 4
• In fact, this is exactly what has occurred.
5. Polymorphism in C++
The added points is
The VPTR pointer
VTABLE entries (continued)
called the called
to a table VPTR
are pointers to
(short for Virtual Pointer).
the VTABLE
virtual methods. MyClass
VPTR
VTABLE First
Virtual Method
Second
The VTABLE entries Virtual Method
are ordered in accordance
with the order in which
the methods are declared
with the class.
Copyright 2008 -- Walter Wesley 5
6. Polymorphism in Java
• Polymorphism in Java is implemented in
exactly the same way as in C++ (except for
some minor differences).
• One difference between the two languages
is that the virtual keyword is not a part of
Java. This is because in Java all methods
are potentially virtual, and the virtual
keyword is therefore unnecessary.
Copyright 2008 -- Walter Wesley 6
• The technique of using a pointer (VPTR) to
7. How to Draw Polymorphically
Shape
abstract
void draw();
Circle Triangle Rectangle Polygon
void draw() {...} void draw() {...} void draw() {...} void draw() {...}
Copyright 2008 -- Walter Wesley 7
8. How to Draw Polymorphically
Shape Objects
Each object will draw
based upon what kind of
Vector of object it is.
References to draw
Shape
draw
draw
draw
“Objects are what they are, and they do what they do.”
– W. Duane Wesley
Copyright 2008 -- Walter Wesley 8