gpt4 book ai didi

java - 当静态变量与 Java 中的静态类同名时会发生什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:51:05 26 4
gpt4 key购买 nike

在下面的 java 示例中,谁能准确解释为什么程序的输出是“橙色”? (这是一道面试题)

public class Finder {
public static void main(String[] args){
System.out.println(X.Y.Z);
}
}

class X {
static W Y = new W();
static class Y {
static String Z ="Apple";
}
}

class W {
String Z = "Orange";
}

最佳答案

变量 Y 掩盖了类型 Y。参见 JLS :

6.4.2. Obscuring

A simple name may occur in contexts where it may potentially beinterpreted as the name of a variable, a type, or a package. In thesesituations, the rules of §6.5 specify that a variable will be chosenin preference to a type, and that a type will be chosen in preferenceto a package. Thus, it is may sometimes be impossible to refer to avisible type or package declaration via its simple name. We say thatsuch a declaration is obscured.

限定名称 X.Y.Z 根据以下内容解析:

6.5.2. Reclassification of Contextually Ambiguous Names

...

If the name to the left of the "." is reclassified as a TypeName, then:

  • If the Identifier is the name of a method or field of the type denoted by TypeName, this AmbiguousName is reclassified as an ExpressionName.

  • Otherwise, if the Identifier is the name of a member type of the type denoted by TypeName, this AmbiguousName is reclassified as a TypeName.

  • Otherwise, a compile-time error occurs.

由于类型和变量的正常命名约定,这在实践中不太可能发生。

关于java - 当静态变量与 Java 中的静态类同名时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14027179/

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