gpt4 book ai didi

java - 泛型方法继承

转载 作者:行者123 更新时间:2023-11-30 06:35:25 25 4
gpt4 key购买 nike

问题是关于以下代码块:

public class SomeClass {
public static class A {
public void f(int x) {
System.out.println("1");
}

public void f(Object x) {
System.out.println("2");
}
}

public static class B extends A {
public <T> void f(T x) { // *
System.out.println("3");
}
}
}

* 无法编译,并出现以下错误:

Description Resource Path Location Type Name clash: The method f(T) of type SomeClass.B has the same erasure as f(Object) of type SomeClass.A but does not override it

避免重复:我看过:Type erasure, overriding and generics , Method has the same erasure as another method in type虽然我收到了答案(部分是因为我仍然没有完全理解它)为什么会出现编译错误(以避免由于类型删除而产生歧义?是这样吗?)主要问题是我不'不明白为什么,如果我在 f(Object x)f(T x) 两种方法之间切换,那么代码将如下所示:

public class SomeClass {
public static class A {
public void f(int x) {
System.out.println("1");
}


public <T> void f(T x) {
System.out.println("3");
}

}

public static class B extends A {
public void f(Object x) {
System.out.println("2");
}
}
}

我没有收到编译错误。为什么会发生这种情况?对于第一个代码,我得到编译错误,而对于第二个代码,我没有得到编译错误,这之间的关键区别是什么?希望对此进行一些解释,谢谢!

最佳答案

One of the answers to one of the questions you linked基本上已经解决了这个问题:

For overriding with instance methods you need the overriding method to be a subsignature of the overridden method.

要进一步深入了解这一点,JLS 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.

子签名在 JLS 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.

您正在考虑以下两个签名:

  1. void f(Object x)
  2. <T> void f(T x)

#2 的删除是 void f(Object x) ,因此 #1 是它的子签名。然而,反之亦然是不正确的。

关于java - 泛型方法继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45267273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com