aspose file tools*
The moose likes Java in General and the fly likes Problem in Generics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Problem in Generics" Watch "Problem in Generics" New topic
Author

Problem in Generics

Ishan Pandya
Ranch Hand

Joined: Feb 06, 2012
Posts: 219



getting an error like:

javac Organic.java
Organic.java:10: react(capture#591 of ? extends Organic) in Organic<capture#591
of ? extends Organic> cannot be applied to (Organic)
compound.react(new Organic());
^
Organic.java:11: react(capture#105 of ? extends Organic) in Organic<capture#105
of ? extends Organic> cannot be applied to (Aliphatic)
compound.react(new Aliphatic());
^
2 errors

why is it so that <? extends Organic> is not able to take Organic or its subclass Aliphatic??


OCPJP
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18570
    
    8

The declaration



means that the type of the variable will at run time be Organic<X> for some class X which extends Organic. At compile time the value of X is unknown.

For example, X might be Aliphatic at run time, and so the variable would be an Organic<Aliphatic> variable. And therefore the react(E) method would require a parameter which can be assigned to Aliphatic.

Clearly an Organic object can't be assigned to Aliphatic, since that would be down-casting. That explains why line 10 has the error message. As for line 11, well, for some reason you declared Aliphatic to be a generic object. So the Aliphatic object you have in line 11 is an Aliphatic<Object> object, which can't be assigned to Aliphatic<Aliphatic>. I would change line 14 to read



At least that would make line 11's compiler error go away. Whether it's what your design requires, I have no way of telling.
Ishan Pandya
Ranch Hand

Joined: Feb 06, 2012
Posts: 219

Mr. Paul. i really thank for your great reply.
but seriously i am not getting what exactly you said and what does this program say.
Like how can be the generic type can be sometime "<Alpha>" and sometimes "<Object>" at runtime while declaring the Orgainc object in the main method..?? What does the "type erasure" do after the compilation?
can you please give me the detail reason for that..?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem in Generics