Enums with constructors

suggest change

An enum cannot have a public or protected constructor. If you omit the modifier, the constructor is private, not 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

It is recommended that you keep all fields private and provide getter methods, as there are a finite number of instances for an enum.


If you were to implement an enum as a class instead, it would look something like this. A real enum also implements Comparable and is serialized by name, not by this class:

public class Coin implements java.io.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

Enum constants are technically mutable, so a setter could be added to change the internal structure of an enum constant. However, this is considered very bad practice and should be avoided.

Best practice is to make Enum fields immutable, with final:

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

    private final int value;

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

    ...

}

You may define multiple constructors in the same enum. When you do, the arguments you pass in your enum declaration decide which constructor is called:

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;
    }

    ...

}

Note: The serialized form of an enum constant is only its name. Enum implements Serializable, but the constant’s fields are not written. They do not have to implement Serializable for that mechanism.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents