-->

In Java, when is the constructor for an enumerated

2020-08-10 07:57发布

问题:

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?

回答1:

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.



回答2:

Much like the static() {...} method, the constructors are invoked when the Enum class is first initialized. All instances of the Enum are created before any may be used.

public static void main(String args[]){
   System.out.println(Commands.Save.getShortCut());
}

In this sample, the ctor for both Save and File will have completed before Save.getShortCut() is invoked.

They are invoked sequentially, as declared in the code.



回答3:

Both will be created at the class initialization time as others said. I like to point out that this is done before any static initializers so you can use these enums in static block.