Imagine the following made up example:
public enum Hand {
ROCK(SCISSORS),
PAPER(ROCK),
SCISSORS(PAPER);
private final Hand beats;
Hand(Hand beats) {
this.beats = beats;
}
}
I will get an error Illegal forward reference
for forward referencing SCISSORS
.
Is there a way to handle such forward references in Java?
Or how would you model such a situation, where you have a logical circular reference between several enums values?
You cannot assign
SCISSORS
toROCK
before it is defined. You can, instead, assign the values in a static block.I have seen a lot examples where people use String values in the constructors, but this is more concrete to assign the actual values after they have been declared. This is encapsulated and the
beats
instance variable cannot be changed (unless you use reflection).Output