Java Program to Create an enum class

To understand this example, you should have the knowledge of the following Java programming topics:


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.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges