Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics clarification

Tags:

java

generics

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.

  1. Why am I getting the error?
  2. I would be happy to get a reference to an article that describes this kind of java generics pitfalls.

Thank you!

like image 905
Vitaliy Avatar asked Jan 16 '23 21:01

Vitaliy


1 Answers

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.

like image 131
Jon Skeet Avatar answered Jan 25 '23 14:01

Jon Skeet