/** * 先写构造方法,如果先写RED(1,“红色”)会报错的 */ public enum Color { RED(1,"红色"), GREEN(2,"绿色"), YELLOW(2,"黄色"); private int code; private String name; Color(int code, String name) { this.code = code; this.name = name; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
我们可以以下方式获得枚举类的属性,枚举类会先调用构造方法初始化
Color.GREEN.getCode()
Color.GREEN.getName()