java泛型参数继承_与Java泛型和继承相关的编译错误

为什么在第二个示例中没有任何编译错误,但是在第一个示例中却存在以下编译错误?

SomeConcreateClass.java:1: ISomeBaseInterface cannot be inherited with different arguments: and <>

public class SomeConcreateClass

^

1 error

唯一的区别-在第二个示例中未对类SomeDerivedClass进行参数化.

范例1:

我在这个例子中正确理解吗

public class SomeConcreateClass

extends SomeDerivedClass

implements ISomeInterface

{}

class SomeDerivedClass /*

extends SomeAbstractClass

implements ISomeInterface

{}

abstract class SomeAbstractClass

implements ISomeBaseInterface

{}

interface ISomeInterface extends ISomeBaseInterface

{}

interface ISomeBaseInterface

{}

范例2:

public class SomeConcreateClass

extends SomeDerivedClass

implements ISomeInterface

{}

class SomeDerivedClass /*

extends SomeAbstractClass

implements ISomeInterface

{}

abstract class SomeAbstractClass

implements ISomeBaseInterface

{}

interface ISomeInterface extends ISomeBaseInterface

{}

interface ISomeBaseInterface

{}

更新:

我是否正确理解在下面的示例中,从SomeDerivedClass开始的所有树都将用作原始类型?

SomeBaseClass的第一个参数是List的信息将丢失.

这是正确的吗?

import java.util.List;

public class SomeConcreateClass

extends SomeDerivedClass

implements ISomeInterface

{

public static void main(String[] args) {

SomeConcreateClass c = new SomeConcreateClass();

List lst = c.getT(); //Type mismatch: cannot convert from Object to List

}

}

class SomeDerivedClass

extends SomeBaseClass /*

implements ISomeInterface

{}

class SomeBaseClass

implements ISomeBaseInterface

{

public T getT(){return null;}

}

interface ISomeInterface extends ISomeBaseInterface

{}

interface ISomeBaseInterface

{}

解决方法:

简而言之,使用原始类型(即使用不带类型参数的通用类型)会禁用其后的所有与通用相关的内容.

通常通过以下示例进行演示:

class Foo { public List m() { ... } }

String s1 = new Foo().m().get(0); // Compiles

String s2 = new Foo().m().get(0); // Cannot cast Object to String

您也有类似的情况,但这与继承而不是成员访问有关.

The superclasses (respectively, superinterfaces) of a raw type are the erasures of the superclasses (superinterfaces) of any of its parameterized invocations.

在第一个示例中,SomeDerivedClass是通用的,SomeConcreteClass继承它为原始类型.因此,ISomeBaseInterface< Object>就可以了.通过继承的该分支继承的继承变成其擦除ISomeBaseInterface,但是直接继承的ISomeInterface仍然继承ISomeBaseInterface< Object>.由于无法使用不同的类型参数多次实现相同的通用接口,因此编译器会报告错误.

在第二个示例中,SomeDerivedClass不是通用的,因此原始类型没有问题.

标签:generics,java

来源: https://codeday.me/bug/20191202/2085044.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值