I've created an enum in Java with each element of the enum referencing another enum. I've also implemeneted a getter which would return the referenced instance. Nothing weird or wrong, I'd say. The only difference from the usual enum implementation is the use of another enum as the backing value. I don't use int or any other primitive type.
Then I tried to implement the other enum in the same way and use the first enum as the backing value for its elements. The code compiles fine and nothing appears to be wrong until I called the getter a few times.
See for yourself in the below JUnit test. The assertion fails on the last line.
Why does it fail?
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
enum EN {
DOG(CS.PES),
CAT(CS.KOCKA);
CS v;
EN(CS v) {
this.v = v;
}
public CS getCS() {
return this.v;
}
}
enum CS {
PES(EN.DOG),
KOCKA(EN.CAT);
EN v;
CS(EN v) {
this.v = v;
}
public EN getEN() {
return this.v;
}
}
public class EnumTest {
@Test
public void testValueOfEnum() {
String zvire = "PES";
CS pes = CS.valueOf(zvire);
assertNotNull(pes);
assertNotNull(pes.getEN()); // OK
assertNotNull(pes.getEN().getCS()); // FAIL -- getCS() is null
}
}