To use a contrived example in Java, here's the code:
enum Commands{
Save("S");
File("F");
private String shortCut;
private Commands(String shortCut){ this.shortCut = shortCut; }
public String getShortCut(){ return shortCut; }
}
I have the following test/driver code:
public static void main(String args[]){
System.out.println(Commands.Save.getShortCut());
}
The question is:
In Java, when is the constructor for an enumerated constant invoked? In the above example, I am only using the Save
enumerated constant. Does this mean that the constructor is called once to create Save
only? Or will both Save
and File
be constructed together regardless?
A set of "enumerable constants" is an ordered collection of constants that can be counted, like numbers. That property lets you use them like numbers to index an array, or you can use them as the index variable in a for loop. In Java, such objects are most often known as "enumerated constants."
Example: enum Constructor The constructor takes a string value as a parameter and assigns value to the variable pizzaSize . Since the constructor is private , we cannot access it from outside the class. However, we can use enum constants to call the constructor.
enum can contain a constructor and it is executed separately for each enum constant at the time of enum class loading. We can't create enum objects explicitly and hence we can't invoke enum constructor directly.
We need the enum constructor to be private because enums define a finite set of values (SMALL, MEDIUM, LARGE). If the constructor was public, people could potentially create more value. (for example, invalid/undeclared values such as ANYSIZE, YOURSIZE, etc.). Enum in Java contains fixed constant values.
The constructors are invoked when the enum
class is initialized. Each constructor will be invoked, in member declaration order, regardless of which members are actually referenced and used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With