aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics wildcard declaration doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics wildcard declaration doubt" Watch "Generics wildcard declaration doubt" New topic
Author

Generics wildcard declaration doubt

sentil kumar
Ranch Hand

Joined: Oct 23, 2006
Posts: 74
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

Joined: Feb 07, 2005
Posts: 2367
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generics wildcard declaration doubt
 
Similar Threads
Marcus Green Exam 1, Q
Doubt on Dynamic polymorphism
Generic methods and wildcards
Generics: Shape example does not work as SUN says
Polymorphism example