Can Some one please explain why the line no. 12 gives a compile time error ?
package com.soflow;
import java.util.List;
public abstract class Shape {
}
class Rectangle extends Shape {
private int x, y, width, height;
public void addRectangle(List<? extends Shape> shapes) {
shapes.add(0, new Rectangle()); // compile-time error!
}
}
What I am failing to understand here is that why is it not allowing me to add a subtype of shapes into the "shapes" list ? And why is it complaining at compile time ? I believe compiler can see that there exists an IS-A relation between Rectangle and Shape. I am confused now. Any help is greatly appreciated.
Thanks, Maneesh Sharma
Any help will be appreciated
List<? extends Shape>
List<? extends Shape>
means a list parametrized with any subclass of Shape
, not a list accepting any subclass of shape as its contents. That would just be a List<Shape>
.
Imagine that shapes
was a List<Triangle>
at runtime. This would clearly be an error, since you can't add a Rectangle to a List<Triangle>
.
However, let's consider why List<Rectangle>
, List<Shape>
or List<? super Shape>
List<? super Shape>
would be correct here. In the first case, it's clear: A List<Rectangle>
would accept instances of Rectangle
. In the second, since all Rectangle
instances are assignable to Shape
, they can be put into a List<Shape>
. In the third case, the bound guarantees that the list will accept Shape
by being a superclass of Shape.
Remember the following phrase: "producer extends, consumer super". Here the list is a consumer of added items, so it needs to be super
.
Change List<? extends Shape> shapes
List<? extends Shape> shapes
to List<? super Shape> shapes
List<? super Shape> shapes
or List<Shape> shapes
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.