Thursday, February 7, 2013

What happens when a Static Variable has the same name as a Static Class in Java?


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

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

class
C {
String
Z = "White";
}

What Does It Print? Do not run it in eclipse and tell me the answer. I need to know why as well?

Ans: White


Reason :Outer static variable priority is higher than inner static variable.. 
You're hiding the class Y with a static instance of C named Y. The class Y is still there and can be used.

Try:
System.out.println(X.Y.Z);
System.out.println((new X.Y()).Z);
The output should be:
White
Black

No comments:

Post a Comment