English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (queue)

Java Map collection

Java Set collection

Java Input Output (I/O)

Java Reader/Writer

Other Java topics

Java Enum Constructors

In this Java tutorial, you can understand enumeration constructors with the help of a valid example.

Before learning enumeration constructors, please make sure you understandJava enumeration.

In Java, enumeration classes may contain constructors similar to those of regular classes. These enumeration constructors are

  • private-Accessible within the class
    or

  • package-private - Accessible within the package

Example: enumeration constructor

enum Size {
   //Enumeration constants, call enumeration constructor
   SMALL("Size small."),
   MEDIUM("Size medium."),
   LARGE("Size large."),
   EXTRALARGE("Size extra large.");
   private final String pizzaSize;
   //Private enumeration constructor
   private Size(String pizzaSize) {
      this.pizzaSize = pizzaSize;
   }
   public String getSize() {
      return pizzaSize;
   }
}
class Main {
   public static void main(String[] args) {
      Size size = Size.SMALL;
      System.out.println(size.getSize());
   }
}

Output Result

The size is very small.

In the above example, we create an enum Size. It contains a private enum constructor. The constructor takes a string value as a parameter and assigns the 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 assign SMALL to the enum variable size. Then, the constant SMALL calls the constructor Size with a string parameter.

 Finally, we use size to call getSize().