Below is the code I was experimenting with:
public enum PagesEnum {
PAGE1 {
public static final SectionsEnum SECTION_A = SectionsEnum.SECTION_A;
public static final SectionsEnum SECTION_B = SectionsEnum.SECTION_B;
},
PAGE2 {
public static final SectionsEnum SECTION_C = SectionsEnum.SECTION_C;
public static final SectionsEnum SECTION_D = SectionsEnum.SECTION_D;
}
}
public enum SectionsEnum {
SECTION_A,
SECTION_B,
SECTION_C,
SECTION_D
}
(The goal of experiments is to get a syntax like PAGE1.SECTION_A
, but that's not the focus of this question.)
I am getting the following compiler error in Eclipse:
The field
SECTION_A
cannot be declared static in a non-static inner type, unless initialized with a constant expression
Now I'm a bit puzzled. SECTION_A
is initialized with the enum SectionsEnum.SECTION_A
- why isn't enum a constant expression? I've checked the JLS, enums indeed are not listen in Constant Expressions.
I wonder, why is that so.
PagesEnum
sub type created byPAGE1{}
static? Maybe that's the part that gives you trouble: "...in a non-static inner type...". – Malte HartwigPAGE1{}
to be considered "non-static inner type". But what I don't get is why enum value is not a "constant expression". From my point of view there are few things in Java more constant than an enum value. – lexicoreSECTION_X
will be a constant of an anonymous sub class ofPagesEnum
. Hence, you can never access them for lack of a class name to prefix them. If I remove the static modifier, Eclipse gives me this warning: "The value of the field new MyClass.PagesEnum(){}.SECTION_A is not used". That is the class defining the constants... not accessible by you, as it's anonymous. – Malte Hartwig