Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics wildcard declaration doubt

 
sentil kumar
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public void addRectangle(List<? extends Shape> shapes) {
shapes.add(0, new Rectangle()); // Compile-time error!
}
here Rectangle is a subclass of Shape.
this method can be called with list of Rectangle object. but why the Rectangle object is not allowed to add shape reference.

is the bounded wildcards declaration is allowed only in the method declaration.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by sentil kumar:
public void addRectangle(List<? extends Shape> shapes) {
shapes.add(0, new Rectangle()); // Compile-time error!
}
here Rectangle is a subclass of Shape.
this method can be called with list of Rectangle object. but why the Rectangle object is not allowed to add shape reference.

is the bounded wildcards declaration is allowed only in the method declaration.


You cannot add items to the list when the declaration is an upper-bounded wildcard.

The reason is there is no way for the compiler to check to make sure that the add is legal because there can be many subclasses of Shape.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic