I just answered this question by saying how to solve the compilation problem:
How to use fields in java enum by overriding the method?
But what I don't understand is why the error is happening in the first place.
Here is the example written as an enum:
public enum MyEnum {
FIRST {
@Override
public String doIt() {
return "1: " + someField; //error
}
},
SECOND {
@Override
public String doIt() {
return "2: " + super.someField; //no error
}
};
private String someField;
public abstract String doIt();
}
Here is the exact same thing as abstract classes
abstract class MyClass {
class FIRST extends MyClass {
@Override
public String doIt() {
return "1: " + someField; //no error
}
};
class SECOND extends MyClass {
@Override
public String doIt() {
return "2: " + super.someField; //no error
}
};
private String someField;
public abstract String doIt();
}
In the case of FIRST within the enum implementation it cannot access someField. However in the abstract class case it can.
Additionally adding super fixes the problem, as does removing the private modifier on the field.
Does anyone know why this slight quirk in the behaviour is happening?
this.someFieldinstead ofsomeFieldgenerates the same error message for both enum/class cases:The field Main.MyClass.someField is not visible.