wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Generic Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Generic" Watch "Generic" New topic
Author

Generic

meeta gaur
Ranch Hand

Joined: Dec 05, 2012
Posts: 305


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".


My one regret in life is that I am not someone else.
- Woody Allen
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

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
Compiling errata for K&B, SCJP 6
Doubt on Generics
Polymorphism and Generics - ideas taken from SCJP 6 by K and B
Generic typing confusion in polymorphism
Generics + Polymorphism