can anyone please tell me why this code is not working ??? and one another question i have in my mind regarding this is with what compiler will set the type of the object g when the code is compiled ???
ankur trapasiya wrote:and one another question i have in my mind regarding this is with what compiler will set the type of the object g when the code is compiled ???
Gen1. That is the type of the variable and of the class instantiated. The generic type parameter is lost; if it would be available it would be "A" for the object, "? extends A" for the variable. That is what the compiler checks for, but not the runtime environment; thus "type erasure".
GenericTest.java:33: doE(capture#774 of ? extends A) in Gen1<capture#774 of ? ex
tends A> cannot be applied to (B)
i am not understanding this error that's why i posted question here..
Just think of the following declaration instead of yours:
Would it be legal? - Sure, C is a subclass of A.
But now the concrete type of g is parametrized to C, not A or B.
So what would happen when this line is called?
Oops. The (concrete) method signature is "doE(C)". A "B" is-not a "C".
That is why the compiler won't let you call the method.
The problem is the declaration "? extends A". It is a lower bound for the variable, but not the object. The referenced object can be parametrized to anything else that is subtype. So the compiler can't allow you to call the object with any type at all.
As this can get confusing you should avoid bounds with variables.
@Hauke : i think i got your point ... may be compiler prevents this to stop runtime errors because any of the child of A may come regardless of inheritance hierarchy.....
@seema : yeah i have tested it ... It's working perfectly ...
@Janeice : source is my self... i was testing my generics concepts ...
Seema Kekre wrote:
No compile error. No runtime errors. Except for a warning saying "The type parameter E is hiding type E" at Line 1. Can someone explain this?
You are introducing a method-local type parameter in line 5. This parameter E has nothing to do with the class's type parameter in line 4. As they have the same name E you can't access the class's parameter any more, it is locally hidden within the method. Every reference to E in that method (and same line) now access the method's type parameter (which is distinct from the class's type parameter).
Just rename the method's type parameter and all it's references. The result is certainly not what you wanted, but it is not now, after renaming it is obvious.