|
|
Might be a trivial question but why Generics needs to use wild card in parameterized type declaration.
Here is an example-
abstract class Shape {
public abstract void draw();
}
class Circle extends Shape {
private int x, y, radius;
public void draw() {}
}
class Test{
main(){
List circles = new ArrayList();
drawAll_1(circles); // compilation error
drawAll_2(circles); // works fine
}
}
public static void drawAll_1(List list) {
}
public static void drawAll_2(List<? extends Shape> list) {
for(Shape each : list){
each.draw();
each.add(new Circle()); // compiltation error
}
}
Now even drawAll_2() method does not allow to add any more shapes to each. Then what was the harm in allowing the drawAll_1(List list) to work with any subclass of Shapes.