执行主类后的输出不同 [英] Different output after execution main class

查看:99
本文介绍了执行主类后的输出不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

class X {
    static class Y {
        static String Z = "Result 1";
    }
    static C Y = new C();
}

class C {
    String Z = "Result 2";
}  

有时输出结果1,有时输出结果2。你能解释一下原因吗?

Sometime output is "Result 1" and sometime output is "Result 2". Can you explain why?

我正在使用 JDK 1.6_33

推荐答案

这是Java Puzzler#68 - 它应该始终打印结果2 。引用:

This is Java Puzzler #68 - it should always print Result 2. Quote:


事实证明,在这些情况下,有一条规则可以控制程序行为。当
变量和类型具有相同的名称且两者都在范围内时,变量名称优先于
[JLS 6.5.2]。据说变量名称模糊了类型名称[JLS 6.3.2]。同样,
变量和类型名称可能会掩盖包名称。这个规则确实模糊不清,任何依赖它的
程序都可能会使读者感到困惑。

It turns out that there is a rule that governs program behavior under these circumstances. When a variable and a type have the same name and both are in scope, the variable name takes precedence [JLS 6.5.2]. The variable name is said to obscure the type name [JLS 6.3.2]. Similarly, variable and type names can obscure package names. This rule is indeed obscure, and any program that depends on it is likely to confuse its readers.

这篇关于执行主类后的输出不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆