English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans ce tutoriel Java, vous pouvez comprendre les constructeurs d'enumeration avec l'aide d'un exemple valide.
Avant d'apprendre les constructeurs d'enumeration, assurez-vous de comprendreJava Enum.
En Java, les classes d'enumeration peuvent contenir des constructeurs similaires à ceux des classes conventionnelles. Ces constructeurs d'enumeration sont
private-Accèsible à l'intérieur de la classe
ou
package-private - Accèsible dans le paquet
enum Size { //Constantes d'enumeration, appel du constructeur d'enumeration SMALL("Taille petite."), MEDIUM("Taille moyenne."), LARGE("Taille grande."), EXTRALARGE("Taille extra-large."); private final String pizzaSize; //Constructeur d'enumeration privé private Size(String pizzaSize) { this.pizzaSize = pizzaSize; } public String getSize() { return pizzaSize; } } class Main { public static void main(String[] args) { Size size = Size.SMALL; System.out.println(size.getSize()); } }
Output result
The size is very small.
In the above example, we created an enum Size. It contains a private enum constructor. The constructor takes a string value as a parameter and assigns the value to the variable pizzaSize.
Since the constructor is private, we cannot access it from outside the class. However, we can use enum constants to call the constructor.
In the Main class, we assign SMALL to the enum variable size. Then, the constant SMALL calls the constructor Size with a string parameter.
Finally, we use size to call getSize().