Understanding enum's static members initialization
This question already has an answer here:
The enum's constants are themselves initialized by calling the constructor. This means the constructor cannot access the constant since it's not yet created at that time.
In other words, say you have:
enum MyEnum {
FOO, BAR;
private MyEnum() {
// Illegal
// FOO already calls this constructor
System.out.println(FOO);
}
}
FOO
and BAR
are equivalent to:
public static final MyEnum foo;
public static final MyEnum bar;
When the enum class is loaded by the JVM, FOO
and BAR
are created by calling the enum private constructor, something like:
foo = MyEnum(); // name of enum, the params are not relevant
bar = MyEnum();
So Java does not allow you to access that field in the constructor since it is still under creation. You can run the following to verify:
enum MyEnum {
FOO, BAR;
private MyEnum() {
System.out.println("Initializing");
}
}
public static void main(String[] args) {
System.out.println(MyEnum.FOO);
}
Output:
Initializing
Initializing
FOO
"Initializing" is printed twice, one by the creation of FOO
and one by BAR
.
The JLS also says this about enums:
It is a compile-time error to reference a static
field of an enum type from constructors, instance initializers, or instance variable initializer expressions of the enum type, unless the field is a constant variable (§4.12.4).
上一篇: 将“private”添加到枚举字段会更改静态上下文
下一篇: 了解枚举的静态成员初始化