gpt4 book ai didi

java - 无法在泛型方法中返回父类(super class)型

转载 作者:行者123 更新时间:2023-12-03 06:04:54 29 4
gpt4 key购买 nike

一些示例代码:

public class Main {
class SomeType {

}
class A {
protected <T extends SomeType> T createSomething()
{
return null; // Don't worry about this.
}
}
class B extends A {
@Override
protected <T extends SomeType> T createSomething()
{
SomeType orig = super.createSomething();
// do some stuff with orig
return orig;
}
}
}

我在这里犯了什么错误?

上线

return orig;

编译器吐出错误

Type mismatch: cannot convert from Main.SomeType to T

感谢<T extends SomeType> ,我们可以确定T始终是 SomeType 的子类型, 正确的?那么为什么我不能只返回父类(super class)型 SomeType

我已经读过<? extends SuperType> cannot be applied to SuperTypeExplanation of the get-put principle但我不明白它在这里如何应用。

最佳答案

Thanks to <T extends SomeType>, we can be sure that T is always a subtype of SomeType, right?

对。

So why can't I just return the supertype SomeType?

因为它可能不是 T !

这样说 - 想象 SomeTypeObject ,和TString 。您建议此代码应该有效:

String foo() {
return new Object();
}

它以其他方式工作 - 您可以为声明返回父类型的方法返回子类型引用,但这是不同的。

修复很简单 - 只需更改 orig类型为T :

T orig = super.createSomething();

然后编译就没有问题了。

关于java - 无法在泛型方法中返回父类(super class)型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25216255/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com