public abstract class Shape {
public abstract void draw(Canvas c);
}
public class Circle extends Shape {
private int x, y, radius;
public void draw(Canvas c) { ... }
}
public class Rectangle extends Shape {
private int x, y, width, height;
public void draw(Canvas c) { ... }
}
Any drawing will typically contain a number of shapes. Assuming that they are
represented as a list, it would be convenient to have a method in Canvas that draws
them all:
public void drawAll(List shapes) {
for (Shape s: shapes) {
s.draw(this);
}
}
Now, the type rules say that drawAll() can only be called on lists of exactly Shape:
it cannot, for instance, be called on a List
. That is unfortunate, since all
the method does is read shapes from the list, so it could just as well be called on a
List. What we really want is for the method to accept a list of any kind of
shape:
public void drawAll(List shapes) { ... }
There is a small but very important difference here: we have replaced the type
List with List. Now drawAll() will accept lists of
any subclass of Shape, so we can now call it on a List if we want.