4
votes

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.

1
Is the PagesEnum sub type created by PAGE1{} static? Maybe that's the part that gives you trouble: "...in a non-static inner type...".Malte Hartwig
@MalteHartwig I'm OK with PAGE1{} 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.lexicore
Yes, now that you repeat it this way... But anyway, I don't think it would work as you indend: SECTION_X will be a constant of an anonymous sub class of PagesEnum. 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
@watchme Well, "constant variables" actually are listed in "constant expressions".lexicore
@MalteHartwig You are correct, this experiment will most probably fail. I'm fine with this, but it's not in scope of my question.lexicore

1 Answers

2
votes

If you want understand then: that because Java load classes dynamically and enum is class too. So it should be resolved in run-time for initialization.

If you want formal reason: constant expression definition in JLS 15.28