in , ,

Java enum Constructor

Java enum Constructor
Java enum Constructor

Java enum Constructor: In this Java tutorial, you can find out about enum constructors with the help of a working example.

Before you find out about enum constructors, make a point to think about Java enums.

In Java, an enum class may incorporate a constructor like an ordinary class. These enum constructors are either

• private – accessible within the class
or

• package-private – accessible within the package


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 pizzaSize;

   // private enum 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

The size is small.

In the above example, we have made an enum Size. It incorporates a private enum constructor. The constructor takes a string an incentive as a parameter and assigns a value to the variable pizzaSize.

Since the constructor is private, we can’t access it from outside the class. In any case, 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.


Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.

salman khan

Written by worldofitech

Leave a Reply

Java enums

Java enums

Java enum Strings

Java enum Strings