帶建構函式的列舉器

enum 不能有公共建構函式; 但是,私有建構函式是可接受的(列舉的建構函式預設是 package-private ):

public enum Coin {
    PENNY(1), NICKEL(5), DIME(10), QUARTER(25); // usual names for US coins
    // note that the above parentheses and the constructor arguments match
    private int value;

    Coin(int value) { 
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

int p = Coin.NICKEL.getValue(); // the int value will be 5

建議你將所有欄位保密,並提供 getter 方法,因為列舉的例項數量有限。

如果你要將 Enum 實現為 class,它將如下所示:

public class Coin<T extends Coin<T>> implements Comparable<T>, Serializable{
    public static final Coin PENNY = new Coin(1);
    public static final Coin NICKEL = new Coin(5);
    public static final Coin DIME = new Coin(10);
    public static final Coin QUARTER = new Coin(25);

    private int value;

    private Coin(int value){
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

int p = Coin.NICKEL.getValue(); // the int value will be 5

列舉常量在技術上是可變的,因此可以新增一個 setter 來改變列舉常量的內部結構。但是,這被認為是非常糟糕的做法,應該避免。

最佳做法是使用 enhuan4 使 Enum 欄位不可變:

public enum Coin {
    PENNY(1), NICKEL(5), DIME(10), QUARTER(25);

    private final int value;

    Coin(int value){ 
        this.value = value;
    }

    ...

}

你可以在同一列舉中定義多個建構函式。當你這樣做時,你在列舉宣告中傳遞的引數決定了哪個建構函式被呼叫:

public enum Coin {
    PENNY(1, true), NICKEL(5, false), DIME(10), QUARTER(25);

    private final int value;
    private final boolean isCopperColored;

    Coin(int value){
        this(value, false);
    }

    Coin(int value, boolean isCopperColored){ 
        this.value = value;
        this.isCopperColored = isCopperColored;
    }

    ...

}

注意:所有非原始列舉欄位都應該實現 Serializable 因為 Enum 類可以實現。