Sunday, December 29, 2024
Google search engine
HomeLanguagesJavaWhy Enum Class Can Have a Private Constructor Only in Java?

Why Enum Class Can Have a Private Constructor Only in Java?

Every enum constant is static. If we want to represent a group named constant, then we should go for Enum. Hence we can access it by using enum Name.

Enum without a constructor:

enum Day{
 SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}

Enum with a constructor:

enum Size {
 SMALL("The size is small."),
 MEDIUM("The size is medium."),
 LARGE("The size is large."),
 EXTRALARGE("The size is extra large.");
 
 private final String pizzaSize;
 // private enum constructor
 private Size(String pizzaSize) {
    this.pizzaSize = pizzaSize;
 }

 public String getSize() {
    return pizzaSize;
 }
}

Why can’t we have a public enum constructor?

We need the enum constructor to be private because enums define a finite set of values (SMALL, MEDIUM, LARGE). If the constructor was public, people could potentially create more value. (for example, invalid/undeclared values such as ANYSIZE, YOURSIZE, etc.).

Enum in Java contains fixed constant values. So, there is no reason in having a public or protected constructor as you cannot create an enum instance. Also, note that the internally enum is converted to class. As we can’t create enum objects explicitly, hence we can’t call the enum constructor directly.

Java




enum PizzaSize {
  
   // 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 pizzaSize;
  
   // private enum constructor
   private PizzaSize(String pizzaSize) {
      this.pizzaSize = pizzaSize;
   }
  
   public String getSize() {
      return pizzaSize;
   }
}
  
class GFG {
   public static void main(String[] args) {
      PizzaSize size = PizzaSize.SMALL;
      System.out.println(size.getSize());
   }
}


Output

The size is small.
RELATED ARTICLES

Most Popular

Recent Comments