Reputation: 71
I following definitions of the class.
public class Test2<T extends Test3> {
private T t ;
public T foo() {
Test3 test3 = new Test3();
t = test3; // I get compilation error here.**
return t;
}
}
class Test3 {
}
I get compilation error at line t=test3, saying "Type mismatch can not convert from Test3 to T; What is wrong?
Upvotes: 2
Views: 148
Reputation: 77024
What you're doing is equivalent to this:
Integer n = new Number();
and has nothing to do with generics (note that Integer extends Number
). The compiler is indicating you cannot assign a parent type to an instance of a child type, the parent type may not implement all the child type's required methods.
In this case T
is the child type of Test3
, or Test3
itself. So here, you're trying to assign the parent class (T
) to a variable that contains the child class (Test3
) and it fails, just like the example above.
Upvotes: 8
Reputation: 285405
Can a child object variable refer to a parent object?
Just test it without the generics:
public class Foo {
public static void main(String args[]) {
T t = new Test3();
}
}
class T extends Test3 {
}
class Test3 {
}
edit: nevermind, I initially posted as a comment, then posted as an answer... but was too late! :)
Upvotes: 1
Reputation: 23614
Because it is downcast. T can be any class derived from Test3, if you sure (but why you need T, use always Test3) you can use follow explicit casting:
@SuppressWarnings("unchecked")
t = (T)test3;
Upvotes: 0
Reputation: 798526
T
is a subclass of Test3
. As such, unless it is exactly Test3
the assignment will fail since subclasses can be assigned to variables of a superclass type but the reverse is not true.
Upvotes: 2