Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an enum have a constructors for each of its constants

Please look at this link. In his book Effective Java, Joshua Bloch says

Note that the Operation constants are put into the stringToEnum map from a static block that runs after the constants have been created.

Trying to make each constant put itself into the map from its own constructor would cause a compilation error

. This is a good thing, because it would cause a NullPointerException if it were legal.

Enum constructors aren’t permitted to access the enum’s static fields, except for compile-time constant fields.

This restriction is necessary because these static fields have not yet been initialized when the constructors run.

I have two questions

  1. Can Enums have separate constructors for each constant?
  2. Why are compile time constant fields accessible in constructors but not static fields?

Thanks

like image 547
Ankit Avatar asked May 06 '15 07:05

Ankit


People also ask

Can enum have constructors?

Note: The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.

Can enum have multiple constructors?

Yes, they can have more than one constructor.

Does enum have default constructor?

enum constructorsBy default, enums don't require constructor definitions and their default values are always the string used in the declaration.

Can we define constants in enum?

The enum type, introduced in Java 5, is a special data type that represents a group of constants. Using enums, we can define and use our constants in the way of type safety. It brings compile-time checking to the constants.


3 Answers

As for first question: you cannot have separate constructors, but you can work-around this in the following manner:

public enum EnumTest {
    ONE() {
        void init() {
            val = 2;
        }
    },
    TWO() {
        void init() {
            val = 1;
        }
    };

    protected int val;

    abstract void init();

    EnumTest() {
        init();
    }
}

This way you technically have separate initialization methods for different constants.

Another way is to use initializer sections:

public enum EnumTest {
    ONE() {{
            val = 2;
        }},
    TWO() {{
            val = 1;
        }};

    protected int val;
}

As for your second question: constant fields are not accessible during enum construction, because enum constants are accessible for static fields. For example, this code compiles correctly:

public enum EnumTest {
    ONE, TWO;

    public static final String ONE_STRING = ONE.toString();
}

If accessing ONE_STRING from the constructor were allowed, you would either had an endless initialization loop or accessing of not-yet-initialized enum constant.

like image 134
Tagir Valeev Avatar answered Oct 13 '22 06:10

Tagir Valeev


  1. No, and I don't think that is what Bloch means, although it has not been formulated in the best possible way. An enum can have constructors, as the enum Operation in the book has. What Bloch means with "its own constructor" is: when the constructor of Operation runs for that particular constant.

  2. This is already answered by what you quoted above:

    This restriction is necessary because these static fields have not yet been initialized when the constructors run.

like image 31
Jesper Avatar answered Oct 13 '22 04:10

Jesper


The regular rules for constructors apply. You can have as many constructors as you want so long as they have different signatures. Different enum values can then be built using different constructors:

enum StringAndNumber {
    Zero("zero"),
    Five(5),
    Pi("Pi", 3.14159);

    private final String str;
    private final Number num;

    private StringAndNumber(String str) {
        this.str = str;
        this.num = null;
    }

    private StringAndNumber(Number num) {
        this.num = num;
        this.str = null;
    }       

    private StringAndNumber(String str, Number num) {
        this.str = str;
        this.num = num;
    }
}
like image 20
Misha Avatar answered Oct 13 '22 06:10

Misha