Java enum Constructor
In Java, an enum can have a constructor just like any other class. The constructor is called when each value of the enum is initialized. Here is an example of an enum with a constructor:
public enum Size { SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL"); private String abbreviation; private Size(String abbreviation) { this.abbreviation = abbreviation; } public String getAbbreviation() { return abbreviation; } }
In this example, the Size
enum has a constructor that takes a string abbreviation as an argument. The constructor initializes the abbreviation
field for each value of the enum. The getAbbreviation
method can then be used to get the abbreviation for a particular value of the enum.
Note that in Java, the constructor for an enum is always private, even if you don't explicitly declare it as such. This is because the values of an enum are defined by the language itself, and the only way to create instances of the enum is by using the values that are already defined.
Also note that if you define any values of an enum, you must provide a constructor that matches the arguments used to create those values. For example, if you define an enum with a value VALUE1("string1")
, you must provide a constructor that takes a single string argument, like this:
private MyEnum(String value) { this.value = value; }