• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Strange Enum behaviour?

 
Ec Kjellberg
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What happens in this (rather stupid) sample?
It looks like the static variable Enum.next is not initialised when the Enum are and therefore their member variable value is initialised with values from 0 to 2 (instead of 'a' to 'c' as one might think).

The output is at least:
a
0
1
2
a

And the code looks like:



I assume that this is a well defined initialisation order behind this but nevertheless I was a little bit surprised.

If anyone care to elaborate a little bit and maybe explain a little I'd be very happy and maybe a little bit less confused.

Thanks // Ecka
 
Steve Luke
Bartender
Posts: 4181
21
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The enum will be translated to a class file, with each enum constant being a static constant inside the enum class declaration.

Since an enum constant is a static field, it has to be constructed inside a static block. To avoid problems with user-declared static field referring to the enum constants the static block is executed before initialization of the static fields.

If I were to write your enum as a class definition it would look like this (leaving out the built-in enum code):


So the enum constants are constructed before the static field 'next' is initialized.
 
Jelle Klap
Bartender
Posts: 1951
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you really, really want to, and you really, really shouldn't, you could declare an inner class inside the enum. The inner class can declare and initialize static fields before the enum constructor runs, and make them accessible to the constructor.



This modified version of your code sample will actually initialize the member value of Enum.A to char value 'a', Enum.B to char value 'b' and Enum.C to char value 'c', as soon as the Enum is used. The initial Enum.next() call will therefore yield char value 'd' and subsequent calls will continue to increment the value of the static field. So the output should read:
d
a
b
c
e
[ August 15, 2008: Message edited by: Jelle Klap ]
 
Steve Luke
Bartender
Posts: 4181
21
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or move the value initializer into a user-defined static block after the next variable is defined. An example:
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Of course in this particular example, an alternative to get the needed behavior could be this:



Or this:

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic