关于 Java 中方法覆盖的泛型的查询
Query regarding Generics with Method Overriding in Java
案例 - 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 中,接口中的方法没有任何通用数据类型,但 TestGenerics class 中的覆盖方法在方法签名中具有通用数据类型 <T>
。这打破了 method Overriding 完全匹配 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,根据接口方法声明中提供的方法覆盖和泛型的概念,代码工作正常。需要注意的一点是TestGenericsclass中的Overriden方法没有指定泛型类型<T>
。
问题是,为什么在Java.
的Method Overriding的角度来看,为什么Case-1编译失败,Case-2编译成功,反之亦然
任何指点将不胜感激。
参见来自 JLS 的 this section:
An instance method mC
declared in or inherited by class C, overrides from C another method mI
declared in an interface I, iff all of the following are true:
- I is a superinterface of C.
mI
is an abstract
or default method.
- The signature of
mC
is a subsignature (§8.4.2) of the signature of mI
.
以及以下 this section:
The signature of a method m1
is a subsignature of the signature of a method m2
if either:
m2
has the same signature as m1
, or
the signature of m1
is the same as the erasure (§4.6) of the signature of m2
.
通过类型擦除,方法签名没有类型变量:
The erasure of the signature of a generic method has no type parameters.
案例 - 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 中,接口中的方法没有任何通用数据类型,但 TestGenerics class 中的覆盖方法在方法签名中具有通用数据类型 <T>
。这打破了 method Overriding 完全匹配 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,根据接口方法声明中提供的方法覆盖和泛型的概念,代码工作正常。需要注意的一点是TestGenericsclass中的Overriden方法没有指定泛型类型<T>
。
问题是,为什么在Java.
的Method Overriding的角度来看,为什么Case-1编译失败,Case-2编译成功,反之亦然任何指点将不胜感激。
参见来自 JLS 的 this section:
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.