gpt4 book ai didi

java - 为什么 super 方法不可见/无法解决?

转载 作者:搜寻专家 更新时间:2023-11-01 01:51:43 25 4
gpt4 key购买 nike

interface Problematic {
void method();
}
class Parent {
void method(int arg) { }
}

class Child extends Parent {
void test() {
new Problematic() {
@Override public void method() {
// javac error: method method in class <anonymous Problematic> cannot be applied to given types;
// required: no arguments, found: int
method(0);
Child.this.method(0); // works just fine
Child.super.method(0); // works just fine
}
};
}
}

IntelliJ IDEA 也给出警告:

Method 'method()' recurses infinitely, and can only end by throwing an exception

最佳答案

From the Java Language Specification,

If the form is MethodName, that is, just an Identifier, then:

If the Identifier appears in the scope of a visible method declaration with that name (§6.3, §6.4.1), then:

  • If there is an enclosing type declaration of which that method is a member, let T be the innermost such type declaration. The class or interface to search is T.

  • This search policy is called the "comb rule". It effectively looks for methods in a nested class's superclass hierarchy before looking for methods in an enclosing class and its superclass hierarchy. See §6.5.7.1 for an example.

  • Otherwise, the visible method declaration may be in scope due to one or more single-static-import or static-import-on-demand declarations. There is no class or interface to search, as the method to be invoked is determined later (§15.12.2.1).

您正在调用匿名内部类中的方法,该类是 Problematic 的子类型。这使得 Child 成为它的封闭类型。在您的情况下, T 是匿名内部类,因为它是最里面的类型。因此,搜索方法的类是 T,即。 Problematic 的匿名子类。

later the resolution of method invocation expressions的步骤, 决定方法 Problematic#method() 没有参数,因为它没有声明任何参数。因此它不适用并会引发编译器错误。

关于java - 为什么 super 方法不可见/无法解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27337222/

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