Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object Oriented Programming Lecture 11: Polymorphism.

Similar presentations


Presentation on theme: "Object Oriented Programming Lecture 11: Polymorphism."— Presentation transcript:

1 Object Oriented Programming Lecture 11: Polymorphism

2 Polymorphism Sometimes we want to write general purpose code to manipulate items without too much regard as to what kind of items they are Example: General purpose list handling – List x; x.add(whatever);

3 Mechanisms Cheat on the type system (C/C++) Use object refs with run time typing (Java) Generics (C++, next release of Java) Dynamic Binding – Use Interfaces in Java – Use Abstract Classes and Methods in Java (Same technique with Virtual Functions in C++)

4 Cheating (Not Java) class List { public add(void *item); public void *head(); } List mylist; mylist.add(&whatever); Rectangle *r = (Rectangle *)mylist.head();

5 Object References (Java) class List { public add(Object item); public Object head(); } List mylist; mylist.add(any object); Rectangle r = (Rectangle )mylist.head();

6 Using References (Java) Supported by run time type checking, so that the process is type safe, but not checked at compile time. Result is that a program may fail at run time. Used in a series of utility classes (collection classes), see example of Vector later. Only works with objects – Cannot have a list, vector of integers (wrapper classes get around this limitation)

7 Generics (C++/Soon Java) class List { public void add(T item); public T head(); List mylist; mylist.add(r); Rectangle r = mylist.head();

8 Generics Fully type safe Static checking Allows homogeneous lists only (nearly) – Cheating allowed heterogeneous lists

9 Dynamic Binding The last crucial component of OOP – Encapsulation – Inheritance – Dynamic Binding

10 Examples The targets in the PinBallGame program of Budd’s Chapter 7 Shapes in a drawing program (classic) – Mouse10-15.java

11 Shape Program


Download ppt "Object Oriented Programming Lecture 11: Polymorphism."

Similar presentations


Ads by Google