enum - Non-static method cannot be referenced from non-static context

Viewed 1834

Error: java: non-static method a() cannot be referenced from a static context

I get this error on the following code.

enum ENUM
{
  A()
  {
    {
      a();
    }
  }
  ,
  ;
  private void a()
  {}
}

I expect this to compile, but it doesn't.

Changing the access level modifier private from method a() to any other lets the code compile.

What may prevent this code from compiling?

2 Answers

You get this compile error because enum constants like A here are implicitly static. That's the reason we can use the enum constants like eg: ENUM.A in any other class. Thus we cannot call a non-static method from a static context. Refer this documentation for more details on enums

The error message is misleading. It's not limited to enums, or to initializer blocks or anything. The problem is simply that an anonymous inner class cannot access private methods from its enclosing class.

private states that sub-classes should not have visibility, and an anonymous inner class is a sub-class so it makes logical sense.

You can observe the same problem with this example:

class Foo {
    public static void main(String[] args) {
        Foo foo = new Foo(){
            void bar() {
                a();
            }
        };
    }

    private void a(){ /* do nothing */  }
}
Related