Java Generics Clarification

There I, although I understood Java generics, have not yet 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 that the types are incompatible: T required, found A.

  • Why am I getting an error message?
  • I would be happy to get a link to an article that describes similar flaws in java generics.

Thanks!

+4
source share
3 answers

If compiled, it will not be type safe:

 B b = new B(); ba = new A(); SubclassOfA foo = b.<SubclassOfA>getA(); 

The compiler cannot guarantee that a will be an instance of T , and it will not even be able to check it at runtime due to type erasure - therefore, it will not compile.

Generally, Java Generics FAQs cover almost everything.

+10
source

Here is the version that should work:

 class B<T extends A>{ T a; T getA(){ return a; } } 

Client code can be sure that getA () returns a subtype of A, as above, but the compiler can also be sure that it has the right subtype of A

+2
source

T extends A means that T must be a subclass of A , not A In your case, you want something like:

 <T> T getA() { return a; } 

Here is a java generics tutorial .

-3
source

All Articles