Java Enum Methods - return opposite direction enum

后端 未结 6 746
时光说笑
时光说笑 2020-11-27 10:34

I would like to declare an enum Direction, that has a method that returns the opposite direction (the following is not syntactically correct, i.e, enums cannot be instantiat

6条回答
  •  伪装坚强ぢ
    2020-11-27 10:50

    This works:

    public enum Direction {
        NORTH, SOUTH, EAST, WEST;
    
        public Direction oppose() {
            switch(this) {
                case NORTH: return SOUTH;
                case SOUTH: return NORTH;
                case EAST:  return WEST;
                case WEST:  return EAST;
            }
            throw new RuntimeException("Case not implemented");
        }
    }
    

提交回复
热议问题