使用泛型返回类型的覆盖方法 [英] Overriding method with generic return type

查看:164
本文介绍了使用泛型返回类型的覆盖方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个定义以下抽象方法的超类

  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>是 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> for getMainClass() from the type SubFoo needs unchecked conversion to conform to Class<Interface> from the type SuperFoo

    Doesn't Class<Implementation> fall under Class<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 of Class<T> where <T extends Interface>. T is unknown here.

    Class<Impl> is a subtype of Class<? extends Interface>, per subtyping rules.


    some subtyping rules regarding wildcards:

    for any type X

    • A<X> is a subtype of A<? extends X>

    • A<X> is a subtype of A<? super X>

    if S is subtype of T

    • A<? extends S> is a subtype of A<? extends T>

    • A<? super T> is a subtype of A<? 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆