Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different output after execution main class

Tags:

java

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";
}  

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

I am using JDK 1.6_33.

like image 942
Ilya Avatar asked Aug 31 '12 22:08

Ilya


1 Answers

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

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.

like image 150
assylias Avatar answered Sep 21 '22 10:09

assylias