列挙型その4

では複数のコンストラクタを作ってみる。

public class HogeClass2 {
  public enum Hoge4{
    A("A"), B("B", 2), C(3);    //変数名と同じ制約
    
    public String arg;
    public final int i;
    
    //コンストラクタは複数あってもよい
    private Hoge4(){
      this.i = 1;   //final変数を初期化しないとコンパイルエラー
    }
    
    private Hoge4(String arg){
      this();
      this.arg = arg;
      //this.i = 1;   //this()を呼び出しているのでコンパイルエラー
    }

    private Hoge4(int i){
      this.i = i;
    }

    private Hoge4(String arg, int i){
      this.arg = arg;
      this.i = i;
    }
    public void print(){
      System.out.println("arg[" + arg + "], i[" + i + "]");
    }
  }
}
public class Test4 {

  public static void main(String[] args) {
    Hoge4.A.print();
    Hoge4.B.print();
    Hoge4.C.print();
  }
}


実行結果。

arg[A], i[1]
arg[B], i[2]
arg[null], i[3]


ふむう。