简体   繁体   中英

Wildcard compile-time error

Looking at this example in generics:

// abstract class   
public abstract class Shape {
    public abstract void draw(Canvas c);

}

//implementation of shape class
public class Rectangle extends Shape {
    private int x, y, width, height;
    public void draw(Canvas c) { ... }
}

//function to add rectangle object in a list
public void addRectangle(List<? extends Shape> shapes) {
    shapes.add(0, new Rectangle()); // compile-time error!
}

Why is this a compile error? I couldn't figure it out as shapes in the list of type which are the subclass of shape and rectangle is the subclass of Shape.

Please help me to figure out this query.

This is because List< ? extends Shape > List< ? extends Shape > means that the real object passed may be declared as List<Rectangle> or List<Circle> .

If you would try to insert a Rectangle into a list of Circles that would really be a problem.

For the insertion to succeed you need to use super , as in List< ? super Shape > List< ? super Shape > .

This means that the real object passed into this function may be only declared as List<Shape> or even List<Object> . Such lists can definitely contain Rectangles and Circles together ( hey in the latter case, even Apples and Oranges as well ).

This exact example is explained in the Java tutorial :

There is, as usual, a price to be paid for the flexibility of using wildcards. That price is that it is now illegal to write into shapes in the body of the method. For instance, this is not allowed:

 public void addRectangle(List<? extends Shape> shapes) { // Compile-time error! shapes.add(0, new Rectangle()); } 

You should be able to figure out why the code above is disallowed. The type of the second parameter to shapes.add() is ? extends Shape ? extends Shape -- an unknown subtype of Shape . Since we don't know what type it is, we don't know if it is a supertype of Rectangle ; it might or might not be such a supertype, so it isn't safe to pass a Rectangle there.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM