gpt4 book ai didi

java - 外部与 super 类

转载 作者:搜寻专家 更新时间:2023-10-30 19:46:06 27 4
gpt4 key购买 nike

super 是否比外部类有更高的优先级?

考虑我们有三个类:

  1. A级
  2. B级
  3. ClassB 中扩展 ClassA 的匿名类

A类.java:

public class ClassA {
protected String var = "A Var";

public void foo() {
System.out.println("A foo()");
}
}

类B.java:

public class ClassB {
private String var = "B Var";

public void test() {

new ClassA() {
public void test() {
foo();
System.out.println(var);
}
}.test();
}

public void foo() {
System.out.println("B foo()");
}
}

当我调用 new ClassB().test() 时,我得到以下输出(这非常符合预期):

A foo()
A Var

问题:它是在某个地方定义的,内部类首先从父类(super class)获取(方法和成员),然后从外部类获取,还是它依赖于 JVM 编译器实现?我查看了 JLS(§15.12.3) 但找不到任何引用资料,也许它在那里指出但我误解了一些术语?

最佳答案

参见 6.3.1 Shadowing Declarations :

A declaration d of a method named n shadows the declarations of any other methods named n that are in an enclosing scope at the point where d occurs throughout the scope of d.

可能被解释为“foo 的声明(继承自 ClassA)隐藏了任何其他名为 的方法的声明foofoo 出现的位置处在封闭范围 (ClassB) 中,在整个 foo 范围内。"

也相关 - 第 15.12.1 :

15.12.1 Compile-Time Step 1: Determine Class or Interface to Search

The first step in processing a method invocation at compile time is to figure out the name of the method to be invoked and which class or interface to check for definitions of methods of that name. There are several cases to consider, depending on the form that precedes the left parenthesis, as follows:

  • If the form is MethodName, then there are three subcases:
    • If it is a simple name, that is, just an Identifier, then the name of the method is the Identifier. If the Identifier appears within the scope (§6.3) of a visible method declaration with that name, then there must be 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.
    • If it is a qualified name of the form TypeName.Identifier, then [...]
    • In all other cases, the qualified name has the form FieldName.Identifier; then [...]

关于java - 外部与 super 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5867287/

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