From JLS (§8.9):
An enum declaration specifies a new enum type
EnumDeclaration:
ClassModifiersopt enum Identifier Interfacesopt EnumBody
EnumBody:
{ EnumConstants-opt ,opt EnumBodyDeclarations-opt }
As you can see, the body should be defined with enum-constants declared first and other body declarations may follow - not the other way around!
Further, you don't have to use lazy initialization like bohemian suggested you can do it in a simpler manner. According to JLS you can't do:
enum Test {
TEST1, TEST2;
static int x;
Test(){
x = 1; // <-- compilation error!
}
}
but you can use static initializer block:
enum Test {
TEST1, TEST2;
static int x;
static{
x = 1; // works!
}
}
The reason that you CAN use the latter is that static declarations are executed in the same order they were declared - assigning x=1
will occur only after x
was declared, unlike using a constructor. If you want to verify it - you can add System.out.println()
calls to the constructor and static block - you'll see that the constructor is being executed first.