Polymorphism

1,420 views
1,158 views

Published on

Polymorphism Slides

0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,420
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
0
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Polymorphism

  1. 1. Polymorphism Poly → manyMorph → shapes (“behaviors”) Copyright 2008 -- Walter Wesley 1
  2. 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. 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. 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. 5. Polymorphism in C++The added points is The VPTR pointer VTABLE entries (continued)called the calledto a table VPTR are pointers to(short for Virtual Pointer).the VTABLE virtual methods. MyClass VPTR VTABLE First Virtual Method SecondThe VTABLE entries Virtual Methodare ordered in accordancewith the order in whichthe methods are declaredwith the class. Copyright 2008 -- Walter Wesley 5
  6. 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. 7. How to Draw Polymorphically Shape abstract void draw(); Circle Triangle Rectangle Polygonvoid draw() {...} void draw() {...} void draw() {...} void draw() {...} Copyright 2008 -- Walter Wesley 7
  8. 8. How to Draw Polymorphically Shape Objects Each object will draw based upon what kind ofVector of object it is.References to drawShape draw draw draw“Objects are what they are, and they do what they do.” – W. Duane Wesley Copyright 2008 -- Walter Wesley 8

×