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.
Thank you!
If it compiled, it wouldn't be type-safe:
B b = new B();
b.a = new A();
SubclassOfA foo = b.<SubclassOfA>getA();
The compiler can't guarantee that a
will be an instance of T
, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With