English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn how to create an enum class in Java.
To understand this example, you should understand the followingJava ProgrammingTopic:
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.