There I though I understood Java generics until I tried to write the following:
class A{}
class B{
A a;
<T extends A> T getA(){
return a; // does not compile
}
}
I get a compilation error saying the types are incompatible: required T, found A.
- Why am I getting the error?
- I would be happy to get a reference to an article that describes this kind of java generics pitfalls.
Thank you!
If it compiled, it wouldn’t be type-safe:
The compiler can’t guarantee that
awill be an instance ofT, and it can’t even check it at execution-time due to type erasure – so it won’t compile.In general the Java Generics FAQ covers just about everything.