案例 - 1
interface Test{
public void display();
}
public class TestGenerics implements Test{
@Override
public <T> void display() {
System.out.println("done");
}
public static void main(String args[]){
TestGenerics ts = new TestGenerics();
ts.display();
}
}
在案例 1 中,接口(interface)中的方法没有任何通用数据类型,但 TestGenerics 类中的重写方法具有通用数据类型 <T>
在方法签名中。这打破了方法重写与 display() 方法签名完全匹配的规则,并引发编译错误。
案例 - 2
interface Test{
public <T> void display();
}
public class TestGenerics implements Test{
@Override
public void display() {
System.out.println("done");
}
public static void main(String args[]){
TestGenerics ts = new TestGenerics();
ts.display();
}
}
在案例 2 中,代码按照接口(interface)方法声明中提供的方法重写和泛型的概念运行良好。需要注意的一点是TestGenerics类中的Overriden方法没有指定泛型类型<T>
。
问题是,为什么从 Java 方法重写的角度来看,为什么 Case-1 编译失败,而 Case-2 编译成功,反之亦然。
任何指示将不胜感激。
最佳答案
参见this section来自 JLS:
An instance method
mC
declared in or inherited by class C, overrides from C another methodmI
declared in an interface I, iff all of the following are true:
- I is a superinterface of C.
mI
is anabstract
or default method.- The signature of
mC
is a subsignature (§8.4.2) of the signature ofmI
.
并关注this section :
The signature of a method
m1
is a subsignature of the signature of a methodm2
if either:
m2
has the same signature asm1
, orthe signature of
m1
is the same as the erasure (§4.6) of the signature ofm2
.
通过类型删除,方法签名不再包含类型变量:
The erasure of the signature of a generic method has no type parameters.
关于java - 关于 Java 中带有方法重写的泛型的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36516923/