Hello everyone..
This is my first post on this forum. And I'm being nice (I hope) as per agreement
Had a question on enums. I'm using
Java 1.6.
Is there any specific reason why enums don't allow access to static member variables within instance initialization blocks or enum constructors?
For example, see some sample code below. The first uses the usual enum, and includes a static and instance init block. The second uses a class to simulate an enum. Both are functionally similary. However, The class version allows access to j (a static member variable) within instance init block and contructor, but the enum version gives a compiler error "Cannot refer to the static enum field UsualEnum.j within an initializer".
Usual Enum ...
Enum simulated using a class ...
The output of the second version is ...
Instance Init Block of MyEnum
j = 1
Instance Init Block of MyEnum
j = 2
Instance Init Block of MyEnum
j = 3
Instance Init Block of MyEnum
j = 4
Static Init Block of MyEnum, j = 4
VALUE01
VALUE02
VALUE03
VALUE04
Another thing...
In the class version of the above (second one), if I change ...
to
the output changes to
Instance Init Block of MyEnum
j = 1
Instance Init Block of MyEnum
j = 2
Instance Init Block of MyEnum
j = 3
Instance Init Block of MyEnum
j = 4
Static Init Block of MyEnum, j = 0
VALUE01
VALUE02
VALUE03
VALUE04
After four inits, j becomes 0 now. I understand all static blocks run first, including static variable initialisations, in the order that they appear in code. But why reset j to 0? Isn't this initialized when space for static j is created? Looking at this output, it seems that the statement has been split into two: static int j; which runs before any init blocks execute, and a j = 0; runs after the creation of the four static finals, as per the order they appear in code.
If I move the statement to before creating the four static finals, then the program gives the same output irrespective of whether I explicitly init j to 0 or not.
Do let me know. Thanks in advance.
Best regards,
Hamy