English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)/)

Java Reader/Writer

Java Other Topics

Java program to create enum class

Java Examples Comprehensive

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

To understand this example, you should understand the followingJava ProgrammingTopic:

Example1: Create Java enum class program

enum Size{
  //enumeration constants
  SMALL, MEDIUM, LARGE, EXTRALARGE;
  public String getSize() {
  //reference object 
  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) {
     //calling method getSize()
     //Using object SMALL
     System.out.println("The size of the pizza I got is "); + Size.SMALL.getSize());
     //calling method getSize()
     //Using object LARGE
     System.out.println("The size of the pizza I want is "); + Size.LARGE.getSize());
  }
}

Output Result

The size of the pizza I got is small
The size of the pizza I want is large

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

In this case, the compiler automatically converts all constants of the enumeration to its instances. Therefore, we can use constants as objects to call this method.

Size.SMALL.getSize()

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

Java Examples Comprehensive