dsa

Java enum Constructor

In this Java tutorial, you can learn about enum constructors with the help of a working example.

1.enum can contain constructor and it is executed separately for each enum constant at the time of enum class loading.
2.We can’t create enum objects explicitly and hence we can’t invoke enum constructor directly.

In Java, an enum class may include a constructor like a regular class. These enum constructors are either

The enum constructor sets the int field. When the constant enum values are defined, an int value is passed to the enum constructor. The enum constructor must be either private or package scope (default). You cannot use public or protected constructors for a Java enum

Example: enum Constructor

enum Size {
   // enum constants calling the enum constructors 
   SMALL("The size is small."),
   MEDIUM("The size is medium."),
   LARGE("The size is large."),
   EXTRALARGE("The size is extra large.");

   private final String cakeSize;

   // private enum constructor
   private Size(String cakeSize) {
      this.cakeSize = cakeSize;
   }

   public String getSize() {
      return cakeSize;
   }
}

class Main {
   public static void main(String[] args) {
      Size size = Size.LARGE;
      System.out.println(size.getSize());
   }
}

Output:

The size is large.

In the above example, we have created an enum Size. It includes a private enum constructor. The constructor takes a string value as a parameter and assigns value to the variable cakeSize.
Since the constructor is private, we cannot access it from outside the class. However, we can use enum constants to call the constructor.
In the Main class, we assigned LARGE to an enum variable size. The constant LARGE then calls the constructor Size with string as an argument.
Finally, we called getSize() using size.