enum(枚举)的全称为 enumeration, 是 JDK 1.5 中引入的新特性,以下是个人心得到。
乍一看枚举让人一头雾水,这是个神马东西??今天就来认识一下把。
二话不说先上代码。
首先我创建了一Light枚举。如下:
public enum Light {
//构建枚举的实例
RED("red", 1), YELLOW("yellow", 1), GREEN("green", 2);
//枚举的属性
private String type;
private int id;
// 构造函数,枚举类型只能为私有
private Light(String type, int id) {
this.type = type;
this.id = id;
}
//以及set,get方法
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
然后创建了一个类 来使用这个枚举
public class LightMain {
public static void main(String[] args) {
Light light = Light.valueOf("RED"); //根据枚举的名字获得这个枚举实例
System.out.println(light.getType()); //获取枚举实例的属性值
System.out.println(light.getId()); //获取枚举实例的属性值
}
}
这样子就能够获得枚举实例的属性值了。