Possible Duplicate:
Java Enums: Two enum types, each containing references to each other?
In our code we got some weird NPE's concerning Enums. When I searched, I found (more or less) the following case:
public class EnumTest {
public static void main(final String[] args){
System.out.println("------ START ----- ");
System.out.println("BeezleBubs FOO's rockSteady is: " + BeezleBub.FOO.rockSteady);
System.out.println("RockSteady BAR's beezleBub is: " + RockSteady.BAR.beezleBub);
System.out.println("------ END ----- ");
}
public enum RockSteady {
BAR(BeezleBub.FOO);
public final BeezleBub beezleBub;
private RockSteady(final BeezleBub beezleBub) {
this.beezleBub = beezleBub;
System.out.println("Constructing RockSteady, beezleBub = " + beezleBub);
}
}
public enum BeezleBub {
FOO(RockSteady.BAR);
public final RockSteady rockSteady;
private BeezleBub(final RockSteady rockSteady) {
this.rockSteady = rockSteady;
System.out.println("Constructing BeezleBub, rockSteady = " + rockSteady);
}
}
}
For some reason the results are awkward. When run, this test outputs:
------ START -----
Constructing RockSteady, beezleBub = null
Constructing BeezleBub, rockSteady = BAR
BeezleBubs FOO's rockSteady is: BAR
RockSteady BAR's beezleBub is: null
------ END -----
The other thing is that when you switch the System.out.prinln() statements calling the Enums, the initialization of the enums change as well. Resulting in:
------ START -----
Constructing BeezleBub, rockSteady = null
Constructing RockSteady, beezleBub = FOO
RockSteady BAR's beezleBub is: FOO
BeezleBubs FOO's rockSteady is: null
------ END -----
Anyone has a clear explanation of what is happening? It has something to do with state & order, but I can't quite put my finger on it...