使用泛型返回类型的覆盖方法 [英] Overriding method with generic return type
问题描述
假设我有一个定义以下抽象方法的超类
public abstract< T extends Interface>类< T> getMainClass();
现在,如果我想在某些子类中覆盖它,那么
public Class< Implementation> getMainClass(){
返回Implementation.class;
}
我收到关于类型安全性和未检查转换的警告:
类型安全性:
的返回类型
需要未经检查的转换,以符合类型<接口> 类型Class< Implementation>
getMainClass()从SubFoo
类型的SuperFoo
不是类< Implementation>如果
< T extends Interface>
,属于 Class< T>
有没有什么办法可以正确地摆脱警告?
重写方法的返回类型必须是重写方法的子类型
$ b Class< Impl>
不是类的类型< T>
其中< T扩展界面>
。 T是未知的。
Class< Impl>
是 Class的子类型?根据子类型规则扩展接口>
。
有关通配符的一些子类型规则:
对于任何类型X
-
A< X> ;
是A< ;?的子类型A< X>< / code>是< / code>的一个子类型< / code> code> A< ;?如果
S $ c $
$> c>是T的子类型
-
A< ;?扩展S>
是A< ;?的子类型延伸T>
-
A< ;? super T>
是A< ;?的子类型超级S>
更简洁,(
< ;: 表示是子类型)
A< S> <:A< ;?扩展S> <:A< ;?延伸T>
A< T> <:A< ;?超T> <:A< ;?超级S>
Let's say I have a super-class that defines the following abstract method
public abstract <T extends Interface> Class<T> getMainClass();
Now if I want to override it in some sub-class
public Class<Implementation> getMainClass(){ return Implementation.class; }
I get a warning about type safety and unchecked conversion:
Type safety: The return type
Class<Implementation>
forgetMainClass()
from the typeSubFoo
needs unchecked conversion to conform toClass<Interface>
from the typeSuperFoo
Doesn't
Class<Implementation>
fall underClass<T>
if<T extends Interface>
? Is there any way to properly get rid of the warning?解决方案the overriding method's return type must be a subtype of the overridden method's return type.
Class<Impl>
is not a subtype ofClass<T>
where<T extends Interface>
. T is unknown here.Class<Impl>
is a subtype ofClass<? extends Interface>
, per subtyping rules.
some subtyping rules regarding wildcards:
for any type X
A<X>
is a subtype ofA<? extends X>
A<X>
is a subtype ofA<? super X>
if
S
is subtype ofT
A<? extends S>
is a subtype ofA<? extends T>
A<? super T>
is a subtype ofA<? super S>
More concisely, (
<:
means "is a subtype of" )A<S> <: A<? extends S> <: A<? extends T> A<T> <: A<? super T> <: A<? super S>
这篇关于使用泛型返回类型的覆盖方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-