I have a class A
which contains a field of type A
(similar to the way a Node
in an implementation of a linked list has a Node nextNode
) like so:
public class A {
private A otherA;
public A getOtherA() {
return otherA;
}
}
Then I have a class B
with a bounded type parameter of <T extends A>
which attempts to assign the return value from getOtherA()
to a variable of type T
:
public class B<T extends A> {
public B(T t1) {
T t2 = t1.getOtherA();
}
}
The above code produces an error at the line
T t2 = t1.getOtherA();
and reads as
Incompatible types. Required T, Found A.
My question is how (if possible) do I modify the code so that I can treat the return value of getOtherA()
as type T
. After all, t1
is of type T
, T
extends A
and getOtherA()
just returns an object of the same type as the object it belongs to. So why does T#getOtherA()
not have a return type of T
?
It seems to me that my compiler should be satisfied that t1.getOtherA()
always returns an object of type T
, but I suspect that I have a misunderstanding of generics, in which case I'll bite the bullet and just cast each one to my desired type.