Java Data Type How to - Create Self referential enum with immutable parameters








Question

We would like to know how to create Self referential enum with immutable parameters.

Answer

enum Value {/*from ww  w. j  a  v  a 2s . c  o  m*/
    A, B, Z, Y;

    static {
        A.opposite = Z;
        B.opposite = Y;
        Y.opposite = B;
        Z.opposite = A;
    }

    public Value flip() {
        return opposite;
    }

    private Value opposite;


}
public class Main{
  public static void main(String[] args) {         
    for(Value f : Value.values()) {
        System.out.println(f + " flips to " + f.flip());
    }
}
}

The code above generates the following result.