-1

I tired to find out the precedence order , Wrote following code which is behaving peculiar . I expected answer black but it gives white .

Can any one helps me understanding this .

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

class X {
    static class Y {
        static String Z = "Black";
    }

    static C Y = new C();
}

class C {
    String Z = "White";
}
RockAndRoll
  • 2,217
  • 2
  • 14
  • 34
Sachin Sachdeva
  • 10,744
  • 2
  • 45
  • 108
  • 3
    The statement `static C Y = new C();` causes the code to print out 'white' instead of 'black' because this overrides the static member Y of class X. Besides of that, this is horrible code. It is very unreadable. – EllisTheEllice Nov 18 '15 at 07:02
  • 1
    @SkinnyJ i like how this is exactly the same question just with a class `C` instead of `W` and other strings – SomeJavaGuy Nov 18 '15 at 07:05

1 Answers1

3

You have created a name that masks the static class Y (of type C). To get black you'd have to access the class Y. You could do that like,

System.out.println(new X.Y().Z); //<-- prints black

or rename the masking field

static C Z = new C(); // <-- from Y.
Elliott Frisch
  • 191,680
  • 20
  • 149
  • 239