-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,247
  • 2
  • 16
  • 35
T-Bag
  • 10,916
  • 3
  • 54
  • 118
  • 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
  • 198,278
  • 20
  • 158
  • 249