[英]Java type mismatch, cannot convert to return itself as the generic type
It error's on the "return this;" 错误在于“返回此”; line with this: Type mismatch: cannot convert from A to T. 与此匹配:类型不匹配:无法从A转换为T。
public class A<T extends A<T>>{
public T method() {
return this;
}
}
I don't understand why the compiler can't convert from A to T, when A is a suitable candidate for T. 我不明白为什么当A是T的合适候选者时,编译器为什么不能从A转换为T。
Let us assume your code was valid... 让我们假设您的代码有效...
You might have a subclass defined like this 您可能有一个这样定义的子类
public class B extends A<B> {
}
Here type parameter T
is same as type of this
. 这里的类型参数T
与this
类型相同。
Which is why I guess you said 这就是为什么我猜你说
A is a suitable candidate for T A是T的合适人选
Now consider this case 现在考虑这种情况
public class C extends A<B> {
}
which is perfectly valid since B
passes all criteria required for T
. 这是完全有效的,因为B
通过了T
所需的所有条件。
In this case your method declaration in class A
becomes invalid. 在这种情况下,您在类A
方法声明A
变为无效。
(return type is B
but you are returning instance of class C
.) (返回类型为B
但是您正在返回类C
实例。)
So your assumption that 所以你的假设是
A is a suitable candidate for T A是T的合适人选
is invalid. 是无效的。 Hence the error. 因此,错误。
Hope this helps. 希望这可以帮助。
Good luck. 祝好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.