English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In diesem Java-Tutorial können Sie mit Hilfe eines gültigen Beispiels den Enum-Konstruktor verstehen.
Bevor Sie den Enum-Konstruktor lernen, stellen Sie sicher, dass SieJava-Enum。
In Java können Enum-Klassen ähnliche Konstruktoren wie reguläre Klassen enthalten. Diese Enum-Konstruktoren sind
private-Innerhalb der Klasse zugänglich
oder
package-private - Innerhalb des Pakets zugänglich
enum Size { //枚举常量,调用枚举构造函数 SMALL("Größe klein."), MEDIUM("Größe mittel."), LARGE("Größe groß."), EXTRALARGE("Größe extra groß."); private final String pizzaSize; //Privater Enum-Konstruktor 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 create 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().