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(Listshapes) {
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
the method does is read shapes from the list, so it could just as well be called on a
List
shape:
public void drawAll(List shapes) { ... }
There is a small but very important difference here: we have replaced the type
List
any subclass of Shape, so we can now call it on a List
No comments:
Post a Comment