I created a enum with one private member variable.
When i try to access the member variable the compiles states ‘Cannot make a static reference to the non-static field memberVariable’.
If the variable is not private (e.g. protected or package protected) it compiles fine. I don’t understand what the scope of the variable has to do with the type (static, non static) of the implemented abstract function.
Can someone enlighten me?
public enum EnumWithAbstractMethodAndMembers {
TheOneAndOnly(1) {
@Override
public int addValue(final int value) {
return memberVariable + value;
}
};
private final int memberVariable;
private EnumWithAbstractMethodAndMembers(final int memberVariable) {
this.memberVariable = memberVariable;
}
abstract int addValue(int value);
}
The error message is confusing.
The problem is that when you give an enum value code, you are creating an anonymous sub class of the enum. (Its class will be
EnumWithAbstractMethodAndMembers$1) A sub-class cannot access the private members of its super-class, however nested classes can via generated accessor method. You should be able to access the private field, and the error message it gives you appears to be mis-leading.BTW You can use this, but you shouldn’t need to IMHO.
Here is a shorter example I will log as a bug in the error message as it doesn’t lead to a solution to the problem.
Based on Tom Hawkin’s feedback, this example gets the same error message.
for comparison