0

Can you please help me understand java8 compiler error on line k3.

    public class Color {
        private int hue = 10;
        public class Shade {
                public int hue = 20;
        }
        public static void main(String[] args) {
                System.out.println(new Color().hue); // k1
                System.out.println(new Color().new Shade().hue); //k2 
                System.out.println(new Shade().hue); //k3
        }
}

Above code compiles if I comment out k3. k1 outputs 10, k2 outputs 20.

With k3, compilation fails saying:

Color.java:11: error: non-static variable this cannot be referenced from a static context
                System.out.println(new Shade().hue);

Main method is under static context,understood. Where is non-static 'this' variable in this picture. Thanks.

Ram
  • 1,153
  • 4
  • 16
  • 34
  • the problem is that `new Shade()` needs a `Color`-reference. This doesn't have anything to do with the variable access - remove `.hue`, it still won't compile – Hulk Jan 28 '19 at 11:48
  • 1
    If you change the class to `static class Shade`, it will compile. – Hulk Jan 28 '19 at 11:49
  • Thanks @Hulk. But why can't compiler say that in simple terms? – Ram Jan 28 '19 at 11:50
  • 1
    @Ram well you'll have to ask that question to the developer who wrote the compiler ;) On a more serious note: it is really just a special case of trying to access an instance-variable from a static context. – Hulk Jan 28 '19 at 11:52
  • Some IDEs will actually provide clearer messages - eclipse shows "No enclosing instance of type Color is accessible. Must qualify the allocation with an enclosing instance of type Color (e.g. x.new A() where x is an instance of Color )." – Hulk Jan 28 '19 at 11:56

0 Answers0