CSCE 314 Lecture 29

From Notes
Jump to navigation Jump to search

« previous | Wednesday, November 9, 2011 | next »


F-Bounded Polymorphism

Subtype polymorphism results in a dumbed-down object: parent methods return a parent type, not a subtype:

class Point {
    public int x;
    public int y;

    public Point(x,y);

    public Point move(Point a, int dx, int dy);
}

class ColorPoint extends Point {
    public int color;

    pubilc ColorPoint(x,y,c) {
        color = c;
        super(x,y);
    }
}

ColorPoint cp = new ColorPoint(0,0);
cp = cp.move(10,10);  // Type error: move returns Point, not ColorPoint

Parametric polymorphism provides solution:

<T extends Point> T move(T a, int dx, int dy) {
    a.x += dx;
    a.y += dy;
    return a;
}

F-bounded quantification allows us to use the type parameter to appear it its own bound:

interface Movable<T> {
    T move(int x, int y);
}


<T extends Movable<T>> T translate(T a, int x, int y) { /* ... */ }


Even mutually recursive systems:

interface Node<E> {
    List<E> out_edges();
}

interface Edge<N> {
    N source();
    N target();
}

<N extends Node<E>, E extends Edge<N>> void breadthFirstSearch(N n) { /* ... */ }


Co- and Contravariance

class Animal {
    public Animal clone() { return new Animal(); }
    public bool compare(Animal) { /* ... */ }
}

class Panda extends Animal {
    public Panda clone() { return new Panda(); }
    public bool compare(Panda) { /* ... */ }
}

calling Animal's clone(), we get an Animal, but we could get something more if we programmed it differently:

Animal a = new Panda();
// ...
Animal b = a.clone(); // returns a Panda, okay


Covariant Arguments

BAD idea: (not supported in most mainstream programming languages)

Animal a = new Panda();
Animal b = new Animal();
a.compare(b); // type error!

Contravariant Arguments

What if...

class Animal {
    // ...
    public bool compare(Panda) { /* ... */ }
}

class Panda extends Animal {
    // ...
    public bool compare(Animal { /* ... */ }
}

This would actually be safe, but it's never been found useful