方法与类型中的另一种方法具有相同的擦除 - 第2部分 [英] Method has the same erasure as another method in type - part 2

查看:200
本文介绍了方法与类型中的另一种方法具有相同的擦除 - 第2部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全得到这个问题方法有相同的问题擦除作为类型中的另一种方法及其答案。请任何人帮助我理解下面的内容吗?

I completely get this question Method has the same erasure as another method in type and the answer to it. Please can anyone help me understand the below?

尝试难以理解,为什么下面的第二个代码片段会出现编译错误?

Trying hard to digest, why the 2nd code snippet below gives compiler error?

代码1:编译正确

class Parent {
    public void set(Collection<Integer> c) { }
}

class Child extends Parent {
    public void set(Collection<Integer> c) {}
}

Code类:Child类中的 set 方法中的编译器错误。

Code 2: Compiler Error at set method in Child class.

class Parent {
    public void set(Collection<?> c) { }
}

class Child extends Parent {
    public void set(Collection<Integer> c) {}
}

编译器错误


名称冲突:Child类型的方法集(Collection)与set相同的擦除(收集)
类型父但不覆盖它

Name clash: The method set(Collection) of type Child has the same erasure as set(Collection) of type Parent but does not override it


推荐答案

因为第一个示例中的代码覆盖了父项中的方法,所以最终会在子对象上使用一个set方法:

Because your code in the first example is overriding the method from the parent, you end up with one set method on the child object:

 public void set(Collection<Integer> c) {}

这显然很好。

在你的第二个例子中,你没有覆盖超类型的方法(因为覆盖方法不是你试图覆盖的方法的子签名)。因此,两种方法必须可以存在于子类型上。

In your second example you are not overriding the method on the super-type (since the over-riding method is not a sub-signature of the method you're trying to override). Therefore it must be possible for both methods to exist on the child type.

//from parent:
public void set(Collection<?> c)

//from child:
public void set(Collection<Integer> c)

在类型擦除之后,不可能:

Which, after type erasure, isn't possible:

//from parent:
public void set(Collection c)

//from child:
public void set(Collection c)

这篇关于方法与类型中的另一种方法具有相同的擦除 - 第2部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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