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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With