Java enum Constructor

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

  1. private - accessible within the class
  2. package-private - accessible within the package.

So, enum constructor is more or like a strategy to access data.


\begin{lstlisting}
enum Size {
\par
// enum constants calling the enum construct...
...ze size = Size.SMALL;
System.out.println(size.getSize());
}
}
\end{lstlisting}

The output for the above code block will be The size is small. 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 pizzaSize. 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 SMALL to an enum variable size. The constant SMALL then calls the constructor Size with string as an argument. Finally, we called getSize() using size.