Polymorphism Giuseppe Attardi Antonio Cisternino Generic programming l

  • Slides: 24
Download presentation
Polymorphism Giuseppe Attardi Antonio Cisternino

Polymorphism Giuseppe Attardi Antonio Cisternino

Generic programming l l Code reuse is clearly a good idea Often an algorithm

Generic programming l l Code reuse is clearly a good idea Often an algorithm can be applicable to many objects Goal is to avoid rewriting as much as possible Types introduce great benefits but also may limit code reuse: int sqr(int i, int j) { return i*j; } double sqr(double i, double j) {return i*j; } The notion of sqr is unique but we must define it twice because of types l Languages offer mechanisms to address this problem l

Polymorphism The ability of associate more than one meaning to a name in a

Polymorphism The ability of associate more than one meaning to a name in a program l We have already seen two kinds of polymorphism: l – Subtype/inclusion (inheritance) – Overloading Polymorphism is the fundamental mechanism for generic programming l There are other kinds of polymorphism l

Classification of Polymorphism Parametric Universal Inclusion Polymorphism Overloading Ad hoc Coercion

Classification of Polymorphism Parametric Universal Inclusion Polymorphism Overloading Ad hoc Coercion

Universal vs. ad hoc polymorphism l l With overloading an implementation for each signature

Universal vs. ad hoc polymorphism l l With overloading an implementation for each signature is required We provide ad hoc solutions for different objects Inheritance instead allows defining algorithms that operate on all classes of objects that inherit from a given class In this case a single (universal) solution applies to different objects

Implementing Polymorphism l Dynamic method dispatch l C++ adds a v-table to each object

Implementing Polymorphism l Dynamic method dispatch l C++ adds a v-table to each object from a class having virtual methods

Containers l Example: Java Vector v = new Vector(); v. add. Element("Pippo"); v. add.

Containers l Example: Java Vector v = new Vector(); v. add. Element("Pippo"); v. add. Element(new Integer(2)); l Signature of add. Element: void add. Element(Object x); l The argument is of type Object because the container may contain any type of object

Problem with containers Inserting an object in a vector we loose type information l

Problem with containers Inserting an object in a vector we loose type information l In our example we implicitly upcast from String to Object: l v. add. Element("Pippo"); l Extracting the second element with the wrong cast produces a runtime error: Integer i = (Integer)v. element. At(0);

Weakest constraint programming l Where do we assume something about objects that we manipulate?

Weakest constraint programming l Where do we assume something about objects that we manipulate? class Vector { Object[] v; int size; public Vector() { v = new Object[15]; size = 0; } public add. Element(Object e) { if (size == v. length) { Object[] w = new Object[](2 * size); w. copy(v, 0, size); v = w; } v[size++] = e; }} l We assume only assignment operations and arrays: operation available on all objects

Can we sort our vector? How to add a method for sorting a vector?

Can we sort our vector? How to add a method for sorting a vector? We do not have enough information on our objects: no comparison operation is available l Our vector is too generic! l Two solutions: l l – accept only objects that implement an interface (i. e. IComparable) that exposes a method to compare objects public void add. Element(IComparable e) {…} – Pass a functional object: an object which implements an interface for comparing Object instances (i. e. IComparator) public void Sort(IComparator c) {…} interface IComparator { int compare(Object x, Object y); }

Abstract as much as possible! To express generic code with subtype polymorphism we should

Abstract as much as possible! To express generic code with subtype polymorphism we should abstract the essence of the operations required on the objects we want to manipulate l Risk is over-abstraction: once defined our vector we can’t easily add a sort method l Another issue: inheritance relies on explicit annotation of our types and changes are hard to perform l

Iterating over a collection A common programming pattern is to enumerate the elements of

Iterating over a collection A common programming pattern is to enumerate the elements of a collection l It doesn’t really matter how the collection is organized l We can implement a class per collection type whose objects. Interface enumerates the elements. l Example: l Enumeration elements() { return ? ? ? ; } void print. Collection(Enumeration e) { while (e = has. More. Elements()) { Object o = e. next. Element(); System. out. println(o); }}

Question l Which class implements method elements? – Class Vector – Use overloading and

Question l Which class implements method elements? – Class Vector – Use overloading and singleton class Enumeration { static Enumeration get. Enumeration(Vector v){ return v. elements(); } // Other collections’ enumerators } l Thus we can add enumerators to existing collections

Enumerator for Vector class Vector. Enum implements Enumeration { int idx; Vector v; bool

Enumerator for Vector class Vector. Enum implements Enumeration { int idx; Vector v; bool has. More. Elements() { idx < v. size(); } Object next. Element() { return v. element. At(idx++); } Vector. Enum(Vector v) { idx = 0; this. v = v; // why it is not copied? } }

Is the enumerator up to date? l l l To ensure that the enumerator

Is the enumerator up to date? l l l To ensure that the enumerator is consistent the vector should be copied into the enumerator This isn’t reasonable: memory wasted and we iterate on a different vector! There is no way to ensure that the enumerator is consistent with the vector Possible solution: introduce a “version” of the vector Each time the vector is modified the version is incremented Enumerator compares the version of the vector with the one at time of creation

Event handling in GUI l l Before Java 1. 1 OO GUI frameworks were

Event handling in GUI l l Before Java 1. 1 OO GUI frameworks were based on sub-typing GUI can be easily described using generic programming: buttons are a subtype of control which is a special window Containers of graphical widgets operates on controls, irrespective of their types Event dispatching and handling is dealt by virtual methods – hence by default is delegated to the super-type

Java AWT Event Model class Component { int x, y; bool handle. Event(Event e);

Java AWT Event Model class Component { int x, y; bool handle. Event(Event e); } class Button extends Component { String text; bool handle. Event(Event e) { } … } class Window extends Component Frame extends Window { … } }

Event handling class My. Button extends Button { boolean handle. Event(Event e) { switch

Event handling class My. Button extends Button { boolean handle. Event(Event e) { switch (e. type) { case Event. MOUSE_UP: … return true; // Event handled! } default: return super. handle. Event(e); }}

Limits of AWT Event Model l Generic programming in this case is quite elegant

Limits of AWT Event Model l Generic programming in this case is quite elegant but inefficient l Propagation of events to a number of handlers, mostly useless l Proliferation of classes: one for each object with different behavior

Alternative l l l Event Delegation model Observer Pattern (aka publish/subscribe) Observable has set

Alternative l l l Event Delegation model Observer Pattern (aka publish/subscribe) Observable has set of registered observers Observable notifies its observers when its state changes Handling performed by objects that provide a Listener interface (aka callback, delegate)

Java JDBC l Java Data. Base Connectivity is a specification from Sun for accessing

Java JDBC l Java Data. Base Connectivity is a specification from Sun for accessing databases in Java l Interesting example of generic programming l It implements a driver architecture exploiting the mechanisms of JVM

Overall architecture l l The java. sql package exposes only interfaces The only class

Overall architecture l l The java. sql package exposes only interfaces The only class is Driver. Manager Using the class constructor a driver register itself with the Driver. Manager The programmer performs the following steps: – Load the database driver (a Java class) – Create a connection to a database (using Driver. Manager) – Obtain a Statement and execute the query – Enumerate the rows using a Result. Set

JDBC example Class. for. Name("…"); // Load the driver Connection c = Driver. Manager.

JDBC example Class. for. Name("…"); // Load the driver Connection c = Driver. Manager. get. Connection("…"); Statement s = c. create. Statement(); Result. Set r = s. execute. Query("select …"); while (r. has. Next()) { // Value of second column as String s = r. get. String(2); }

Question Statement is Class or Interface? l Connection, Statement are Interfaces l Through the

Question Statement is Class or Interface? l Connection, Statement are Interfaces l Through the Driver. Manager the program obtains an object of unknown type which implements the Connection interface l The same applies to all the other interfaces: through the connection an object implementing Statement is obtained, and so on and so forth l