静态变量与Java中的静态类名称相同时会发生什么? [英] What happens when a Static Variable has the same name as a Static Class in Java?
问题描述
在下面的java示例中,有人可以解释为什么程序的输出是橙色吗? (这是一个面试问题)
In the java example below, can anyone explain exactly why the output of the program is "Orange" ? (this is an interview question)
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 :
The variable Y obscures the type Y. See the JLS:
6.4.2。隐藏
6.4.2. Obscuring
一个简单的名称可能出现在上下文中,它可能被
解释为变量,类型或包的名称。在这些
的情况下,§6.5的规则规定变量将被选择为优先于类型的
,并且将优先选择类型为
的类型。因此,有时可能无法通过其简单名称引用
可见类型或包声明。我们说
这样的声明是模糊的。
A simple name may occur in contexts where it may potentially be interpreted as the name of a variable, a type, or a package. In these situations, the rules of §6.5 specify that a variable will be chosen in preference to a type, and that a type will be chosen in preference to a package. Thus, it is may sometimes be impossible to refer to a visible type or package declaration via its simple name. We say that such a declaration is obscured.
符合条件的名称XYZ根据以下方式解析:
The qualified name X.Y.Z is resolved according to:
6.5.2。上下文不明确名称的重新分类
6.5.2. Reclassification of Contextually Ambiguous Names
...
如果名称位于。左侧。被重新分类为TypeName,然后:
If the name to the left of the "." is reclassified as a TypeName, then:
-
如果标识符是TypeName表示的类型的方法或字段的名称这AmbiguousName被重新归类为ExpressionName。
If the Identifier is the name of a method or field of the type denoted by TypeName, this AmbiguousName is reclassified as an ExpressionName.
否则,如果该标识符是一个成员类型由类型名表示的类型的名称,这AmbiguousName被重新分类作为TypeName。
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.
由于类型和变量的正常命名约定,这在实践中不太可能发生。
This is unlikely to occur in practice because of the normal naming conventions for types and variables.
这篇关于静态变量与Java中的静态类名称相同时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!