This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Problem in Generics" Watch "Problem in Generics" New topic

Problem in Generics

Ishan Pandya
Ranch Hand

Joined: Feb 06, 2012
Posts: 219

getting an error like:

javac react(capture#591 of ? extends Organic) in Organic<capture#591
of ? extends Organic> cannot be applied to (Organic)
compound.react(new Organic());
^ 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??

Paul Clapham

Joined: Oct 14, 2005
Posts: 18541

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..?
It is sorta covered in the JavaRanch Style Guide.
subject: Problem in Generics
Similar Threads
Generic upper bounded wildcard instantiation known at run time
Doubt in Devaka's Final Exam Question.
overloading example from examlab
Generics and use of wildcard