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.
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.
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 ]
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Or move the value initializer into a user-defined static block after the next variable is defined. An example:
Joined: Jul 11, 2001
Of course in this particular example, an alternative to get the needed behavior could be this:
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus