package test3;
public final class Program {
public static void main(String[] args) {
// System.out.println(State.ON);
// System.out.println(State.OFF);
System.out.println( Color.getName(1));
Light[] allLight = Light.values();
for (Light aLight : allLight) {
System.out.println("当前灯name:" + aLight.name());
System.out.println("当前灯ordinal:" + aLight.ordinal());
System.out.println("当前灯:" + aLight);
}
for (State item : State.values()) {
System.out.println(item);
System.out.println(State.valueOf(item.name()));
}
}
}
enum State {
ON(1), OFF(0);
int value = 1;
State(int value) {
this.value = value;
}
}
enum Light {
// 利用构造函数传参
RED(1), GREEN(3), YELLOW(2);
// 定义私有变量
private int nCode;
// 构造函数,枚举类型只能为私有
private Light(int _nCode) {
this.nCode = _nCode;
}
@Override
public String toString() {
return String.valueOf(this.nCode);
}
}
enum Color {
RED("红色", 1), GREEN("绿色", 2), BLANK("白色", 3), YELLO("黄色", 4);
// 成员变量
private String name;
private int index;
// 构造方法
private Color(String name, int index) {
this.name = name;
this.index = index;
}
// 普通方法
public static String getName(int index) {
for (Color c : Color.values()) {
if (c.getIndex() == index) {
return c.name;
}
}
return null;
}
// get set 方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}