The syntax sugar provided by Java's enum
facility can sometimes be a little confusing. Consider this example, which does not compile:
public enum TestEnum {
FOO("foo") {
public void foo() {
helper(); // <- compiler error
}
};
String name;
TestEnum(String name) {
this.name = name;
}
public abstract void foo();
private void helper(){
// do stuff (using this.name, so must not be static)
}
}
Can anyone explain why the compiler says
Non-static method 'helper()' cannot be referenced from a static context
How exactly is this context static?
You can make this compile by changing the call to this.
helper()
(here is one confusing point: if we really are in a "static context" like the compiler suggests, how can "this
" work?) or by increasing the visibility of helper()
to default level. Which would you prefer? Also, feel free to suggest a better question title :-)
Edit: I found some discussion about this - but no real answers. My colleague thinks the fact that that this.helper()
works is actually a compiler bug. And indeed with newer Java versions it seems not to work (although super.helper()
does): "cannot find symbol helper()". (Although there's something odd going on: after trying with different Java versions I can't get this.helper()
to compile again with any of them...)