问题描述
我完全得到这个问题及其答案。请任何人帮助我理解下面的内容吗?
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) {}
}
编译器错误
推荐答案
因为第一个示例中的代码覆盖了父项中的方法,所以最终会在子对象上使用一个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部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!