下面的代码:为什么这个覆盖方法声明会产生编译错误?
class Parent {
public void method(List parameter){
}
}
class Child extends Parent {
public void method(List<String> parameter) {
}
}
失败,出现以下错误编译:
Parent.java:12: error: name clash: method(List<String>) in Child and method(List) in Parent have the same erasure, yet neither overrides the other
public void method(List<String> parameter) {
^
1 error
但我检查JLS8在§8.4.8.1说:
An instance method mC declared in or inherited by class C, overrides from C another method mA declared in class A, iff all of the following are true:
...
The signature of mC is a subsignature (§8.4.2) of the signature of mA.
...
而且在§8.4.2中它说:
The signature of a method m1 is a subsignature of the signature of a method m2 if either:
...
the signature of m1 is the same as the erasure (§4.6) of the signature of m2.
在这种情况下,原始和覆盖方法声明都具有相同的擦除,那么为什么编译失败?
'列表'不是'List'的擦除,所以按照你所引用的规范,它不是一个子签名。我认为你有'm1'和'm2'混在一起。 –
4castle
它们是不是都被认为是类型擦除到'List
它们都被擦除为“List”,但您引用的规范并不是关于它们是否具有共同的擦除,而是关于子类的方法是否是超类的擦除方法。如果父类具有'List'且子类具有'List',那么你会没事的。 –
4castle