Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, when is the constructor for an enumerated constant invoked?

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?

like image 700
Umair Avatar asked Sep 04 '09 19:09

Umair


People also ask

What is enumeration constant in Java?

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."

What is the use of constructor in enum in Java?

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.

Can enum have constructor Java?

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.

Does enum need a constructor?

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.


1 Answers

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.

like image 158
erickson Avatar answered Sep 23 '22 18:09

erickson