Home >Java >javaTutorial >How does java define the Enum class to implement value and description?
In computer programming languages such as C and Java, the enumeration type (Enum) is a special data type that can define a set of predefined values for a variable. constant. When using an enumeration type, the value of the enumeration type variable must be one of its predefined values.
Before JDK5, the Java language did not support enumeration types, and could only use classes to simulate and implement enumeration types.
/** 订单状态枚举 */public final class OrderStatus { /** 属性相关 */ /** 状态取值 */ private final int value; /** 状态描述 */ private final String description; /** 常量相关 */ /** 已创建(1) */ public static final OrderStatus CREATED = new OrderStatus(1, "已创建"); /** 进行中(2) */ public static final OrderStatus PROCESSING = new OrderStatus(2, "进行中"); /** 已完成(3) */ public static final OrderStatus FINISHED = new OrderStatus(3, "已完成"); /** 构造函数 */ private OrderStatus(int value, String description) { this.value = value; this.description = description; } /** 获取状态取值 */ public int getValue() { return value; } /** 获取状态描述 */ public String getDescription() { return description; } }
JDK5 provides a new type-Java enumeration type. The keyword enum can convert a set of named values The finite collection is created as a new type, and these named values can be used as constants, which is a very useful feature.
/** 订单状态枚举 */public enum OrderStatus { /** 常量相关 */ /** 已创建(1) */ CREATED(1, "已创建"), /** 进行中(2) */ PROCESSING(2, "进行中"), /** 已完成(3) */ FINISHED(3, "已完成"); /** 属性相关 */ /** 状态取值 */ private final int value; /** 状态描述 */ private final String description; /** 构造函数 */ private OrderStatus(int value, String description) { this.value = value; this.description = description; } /** 获取状态取值 */ public int getValue() { return value; } /** 获取状态描述 */ public String getDescription() { return description; } }
In fact, the Enum type is a syntax sugar, and the compiler helps us parse and compile the syntax. Through decompilation, you can see that Java enumeration actually generates a class after compilation, which inherits java.lang.Enum and adds common methods of enumeration types such as values() and valueOf().
The above is the detailed content of How does java define the Enum class to implement value and description?. For more information, please follow other related articles on the PHP Chinese website!