Java Enum linking to another Enum

Mister Aqua :

I would like to have enumerator in Java having other enum as attribute.

public enum Direction {
    Up(Down),
    Down(Up),
    Left(Right),
    Right(Left);

    private Direction opposite;

    Direction(Direction opposite){
        this.opposite = opposite;
    }
}

So I have different Direction, and for each I want to know the opposite. It is working fine for Down and Right, but I can't initialize Up because Down is not known yet (same fort Left).

How can I edit enum variables after initialisation ?

Pankratiew Alexandr :

One of the possible solution - you can encapsulate this login within the method

public Direction getOpposite() {
   switch (this) {
      case Up:
         return Down;
      case Down:
         return Up;
      case Left:
         return Right;
      case Right:
         return Left;
   }
   return null;
}

It will be the same interface for classes that will use this enum

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=3622&siteId=1