Java - Enums - Logical circular reference [duplicate]
Asked Answered
E

1

4

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?

Extant answered 20/12, 2016 at 12:33 Comment(5)
Which error? please specifyThicket
Updated with Illegal forward reference error information.Extant
You can use a switch inside a method.Ulla
I actually take it back. This is a duplicate... of the first result from the google search of 'Cannot reference a field before it is defined'Thicket
I recommend you to read brickydev.com/enum-circular-dependency-in-javaChowder
A
12

You cannot assign SCISSORS to ROCK 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).

public enum Hand {
    ROCK,
    PAPER,
    SCISSORS;

    private Hand beats;

    static {
        ROCK.beats = SCISSORS;
        PAPER.beats = ROCK;
        SCISSORS.beats = PAPER;
    }

    public Hand getBeats() {
        return beats;
    }

    public static void main(String[] args) {
        for (Hand hand : Hand.values()) {
            System.out.printf("%s beats %s%n", hand, hand.getBeats());
        }
    }
}

Output

ROCK beats SCISSORS
PAPER beats ROCK
SCISSORS beats PAPER
Archery answered 20/12, 2016 at 12:37 Comment(2)
Why downvoted this? It actually looks good to meAnkylose
The code before the edit did not work because of the final modifier on the beats field.Extant

© 2022 - 2024 — McMap. All rights reserved.