Java Program to Create an enum class

Java Program to Create an enum class

In this example, we will learn to create an enum class in Java.

Example 1: Java program to create an enum class

enum Size{

  // enum constants
  SMALL, MEDIUM, LARGE, EXTRALARGE;

  public String getSize() {

  // this will refer to the object SMALL
  switch(this) {
    case SMALL:
      return "small";

    case MEDIUM:
      return "medium";

    case LARGE:
      return "large";

    case EXTRALARGE:
      return "extra large";

    default:
      return null;
     }
  }

  public static void main(String[] args) {

     // call the method getSize()
     // using the object SMALL
     System.out.println("The size of Pizza I get is " + Size.SMALL.getSize());

     // call the method getSize()
     // using the object LARGE
     System.out.println("The size of Pizza I want is " + Size.LARGE.getSize());
  }
}

Output

The size of Pizza I get is small
The size of Pizza I want is large

In the above example, we have created an enum class named Size. The class contains four constants SMALL, MEDIUM, LARGE, and EXTRALARGE.

Here, the compiler automatically converts all the constants of the enum into its instances. Hence, we can call the method using the constant as objects.

Size.SMALL.getSize()

In this call, the this keyword is now associated with the SMALL object. Hence, the value small is returned.

To learn more, visit Java enum and enum Class.