enum TrafficSignal { //this will call enum constructor with one String argument RED("wait"), GREEN("go"), ORANGE("slow down"); private String action; public String getAction() { return this.action; } // enum constructor - can not be public or protected TrafficSignal(String action){ this.action = action; System.out.println(this.action); } } public class EnumConstructorExample{ public static void main(String args[]) { // Only one Enum object initialized/instaniated TrafficSignal c1 = TrafficSignal.GREEN; } }
Output:
wait go slow down
I am just wondering why the output would give the information of all the other Enum types despite the fact I only initialized one enum object (TrafficSignal.GREEN
).
Advertisement
Answer
All the enum’s objects instantiated automatically when class loads
You said:
despite the fact I only initialized one enum object (TrafficSignal.GREEN).
Incorrect. You did not instantiate an enum object.
You accessed an already-existing object of the enum class. That object was instantiated when the enum’s class was loaded.
Indeed, all of the enum’s objects were instantiated when the class loaded. As part of instantiating one object for each of the constant names, its constructor is automatically called. All this happened when the enum class was loaded. So all this happened before your code was executed. The class used in your code must first be loaded before your code can execute. So, three named constants mean the constructor is called three times, each time printing the action
member field value before you gained access to the object referenced by the constant named GREEN
.