I have these simple classes:
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) { ... }
}
These classes can be drawn on a canvas:
public class Canvas {
public void draw(Shape s) {
s.draw(this);
}
}
I would like to put all Circle and Rectangle objects in a single List and draw all of them in a single iteration statement, like this:
public void drawAll(List<? extends Shape> shapes) {
for (Shape s : shapes) {
s.draw(this);
}
}
Everything compiles.
The problem begins if I make a test class and try to create a list like this:
public class Main {
public static void main(String[] args) {
Canvas canvas = new Canvas();
List<? extends Shape> list = new ArrayList<>();
Circle circle = new Circle();
Rectangle rectangle = new Rectangle();
list.add(circle); // The method add(capture#1-of ? extends Shape) in the type List<capture#1-of ? extends Shape> is not applicable for the arguments (Circle)
canvas.drawAll(list);
}
}
As is documented in the code, I cannot add Circle and Rectangle objects to the List.
Question: how should I modify the code such, that I can construct a
List<? extends Shape>
and next iterate over that List to draw the shapes.
thanks in advance.
Post Edit: Thanks! That was quite a breakthrough. Should have given the credits to SpaceTrucker and his crucial PECS link, but that wasn't possible. For some reason I had told myself that I should use extends and never questioned that assumption since.