•JDK1.5After that, you can use the enum keyword to define the enumeration type , the grammatical structure is as follows:
[public] enum Enumeration name[implements Interface list] {
Enumeration object1[, Enumeration object2] [,… ];
[Member variables 1;]
[Member variable2;]
[…]
##[(static or non-static)Code block
[Construction method1]
[Construction method2##]
[…]
#[Normal method1]
[Normal method2]
[…]
[Abstract method1]
[Abstract method2]
[…]## }
public enum Color { RED(1, "红色"), GREEN(2, "绿色"), BLUE(3, "蓝色"); private int value; private String label; private Color(int value, String label) { this.value = value; this.label = label; } public int getValue() { return value; } public String getLabel() { return label; } }
You can define abstract objects directly in the enumerationAt this time, each
EnumerationObjects need to implement this abstract method, as shown in the following exampleenum Color {
RED {
public String getLabel() {
return "红颜色";
}
},
GREEN {
public String getLabel() {
return "绿颜色";
}
};
public abstract String getLabel();
}
public class Test {
public static void main(String[] args) {
for (Color color : Color.values()) {
String label = color.getLabel();
System.out.println(label);
}
}
}
•Enumeration noun
Enumeration Object: Get a specified enumeration object, as in the following example:
static T[] values()
: Get all enumeration objects in the custom enumeration, as in the following exampleEnumeration types can be used in
•switch, as shown in the following example: Enum class is an abstract class, which is the parent class of the Java language enumeration type, that is, enum The keyword-defined enumeration type is equivalent to defining a inheritedjava.lang.Enumsubclass of the abstract classkind. Enum Class construction method: protected Enum(String name, int ordinal) : This constructor receives two parameters, one represents the name of the enumeration, and the other represents the serial number of the enumeration; Detailed introduction to traversal of two enumeration types in JAVA
The above is the detailed content of Java basic knowledge explanation - enumeration type definition. For more information, please follow other related articles on the PHP Chinese website!