Understanding the initialization of static enum members

Bloch Effective Java said the following:

Enum constructor arguments are allowed to access enums static fields, except compile-time constant fields. This restriction is necessary because these static fields have not yet been initialized when the constructors work .

It’s not clear to me, because here is what JLS says:

JLS 8.7 :

The static initializer declared in the class is executed when the class initialized

So, all static members are initialized before the constructor intro is started. What did I miss?

+4
source share
1 answer

. , , .

, , :

enum MyEnum {

   FOO, BAR;

   private MyEnum() {
        // Illegal
        // FOO already calls this constructor
        System.out.println(FOO);
   }

}

FOO BAR :

public static final MyEnum foo;
public static final MyEnum bar;

enum JVM, FOO BAR enum, :

foo = MyEnum(); // name of enum, the params are not relevant
bar = MyEnum(); 

, Java , . :

enum MyEnum {
    FOO, BAR;

    private MyEnum() {
        System.out.println("Initializing");
    }
}

public static void main(String[] args) {
    System.out.println(MyEnum.FOO);
}

:

Initializing
Initializing
FOO

"" , - FOO - BAR.

JLS :

static , , (§4.12.4).

+4

All Articles