aspose file tools
The moose likes Beginning Java and the fly likes Generic Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Generic" Watch "Generic" New topic
Author

Generic

meeta gaur
Ranch Hand

Joined: Dec 05, 2012
Posts: 225


AnimalDoctor6.java:12: error: no suitable method found for add(Object)
animals.add(new Object());
^
method List.add(int,CAP#1) is not applicable
(actual and formal argument lists differ in length)
method List.add(CAP#1) is not applicable
(actual argument Object cannot be converted to CAP#1 by method invocation conversion)
where CAP#1 is a fresh type-variable:
CAP#1 extends Object super: BigCat from capture of ? super BigCat
1 error

Why i can't add "Object" ? ,that is a super of "BigCat".


OCAJP
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 16480
    
    2

You have the usual misunderstanding regarding generic wildcards. When you write "List<? super BigCat>" that means that at runtime, an instance of that type will be an instance of List<X> where X is some supertype of BigCat. It does NOT mean that an instance of that type can contain any object of any supertype of BigCat.

So in your example, an instance of List<? super BigCat> could be a List<Animal>, since Animal is a supertype of BigCat. And you can't add an Object to a List<Animal>. So the compiler rejects that line of code.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generic
 
Similar Threads
Generic typing confusion in polymorphism
Polymorphism and Generics - ideas taken from SCJP 6 by K and B
Generics + Polymorphism
Compiling errata for K&B, SCJP 6
Doubt on Generics