java - 关于 Java 中带有方法重写的泛型的查询

标签 java generics overriding

案例 - 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 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.

关于java - 关于 Java 中带有方法重写的泛型的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36516923/

相关文章:

java - java中带有gui的接口(interface)类?

java - 不要显示 "This app won' t run without google play services”对话框

java - 单击实际 View 中的按钮时如何使用 map View 打开新 View

java - 这两个通用函数之间的区别

c# - 对于传入并需要转换为通用参数的对象,抛出什么适当的异常?

swift - 无法为泛型类型的子类调用初始值设定项

java - 如何使用 java 8 lambda 和流对 Map<YearMonth, List<LocalDate>> 进行排序

objective-c - 强制子类覆盖方法

ruby-on-rails - 如何正确地重写模块混入的方法?

Java:如何查找是否从基类重写了一个方法?