English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans cet exemple, nous allons apprendre à créer une classe d'énumération en Java.
Pour comprendre cet exemple, vous devriez comprendre ce qui suitProgrammation JavaSujet :
enum Size{ //constantes d'énumération SMALL, MEDIUM, LARGE, EXTRALARGE; public String getSize() { //référence de l'objet 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 getSize() method //Using object SMALL System.out.println("The size of the pizza I got is "); + Size.SMALL.getSize()); //call the getSize() method //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 the 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.