Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Last Updated : 28 Jan, 2021

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:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

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.
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!