Consider these enum declarations:
enum Color {
RED(Shape.CIRCLE),
GREEN(Shape.TRIANGLE),
BLUE(Shape.SQUARE);
private final Shape shape;
Color(Shape shape) {
this.shape = shape;
}
Shape getShape() {
return shape;
}
}
enum Shape {
CIRCLE(Color.RED),
TRIANGLE(Color.GREEN),
SQUARE(Color.BLUE);
private final Color color;
Shape(Color color) {
this.color = color;
}
Color getColor() {
return color;
}
}
There are cyclic dependencies between the enum fields. There are no compiler warnings (using Java 8).
However, all these tests will fail in the second line:
@Test
public void testRedAndCircle() {
assertThat(Color.RED.getShape()).isNotNull();
assertThat(Shape.CIRCLE.getColor()).isNotNull(); // fails
}
@Test
public void testCircleAndRed() {
assertThat(Shape.CIRCLE.getColor()).isNotNull();
assertThat(Color.RED.getShape()).isNotNull(); // fails
}
@Test
public void testGreenAndTriangle() {
assertThat(Color.GREEN.getShape()).isNotNull();
assertThat(Shape.TRIANGLE.getColor()).isNotNull(); // fails
}
@Test
public void testBlueAndSquare() {
assertThat(Color.BLUE.getShape()).isNotNull();
assertThat(Shape.SQUARE.getColor()).isNotNull(); // fails
}
How can the null value in the enum field be explained?
It seems that the enum object in the private final fields is not yet completely instantiated.