一 简单应用
package cn.xy.Enum;
public enum TrafficLamp
{
RED,GREEN,YELLOW;
}
TrafficLamp red = TrafficLamp.RED;
System.out.println(red);
System.out.println(red.name());
System.out.println(red.ordinal());
System.out.println(TrafficLamp.valueOf("YELLOW"));
TrafficLamp[] ts = TrafficLamp.values();
for (TrafficLamp t : ts)
{
System.out.println(t.name());
}
结果
RED
RED
0
YELLOW
RED
GREEN
YELLOW
二 复杂应用
package cn.xy.Enum;
public enum TrafficLampComplex
{
// 元素列表必须放在枚举类的最上面
RED(10)
{
@Override
public TrafficLampComplex nextLamp()
{
return GREEN;
}
@Override
public String getValue()
{
return "红灯,时长" + this.getTime();
}
},
GREEN(10)
{
@Override
public TrafficLampComplex nextLamp()
{
return YELLOW;
}
@Override
public String getValue()
{
return "绿灯,时长" + this.getTime();
}
},
YELLOW(5)
{
@Override
public TrafficLampComplex nextLamp()
{
return YELLOW;
}
@Override
public String getValue()
{
return "黄灯,时长" + this.getTime();
}
};
/**
* 时长
*/
private int time;
TrafficLampComplex()
{
}
TrafficLampComplex(int time)
{
this.time = time;
}
/**
* 下一个灯
* @return
*/
public abstract TrafficLampComplex nextLamp();
/**
* 取值
* @return
*/
public abstract String getValue();
public int getTime()
{
return time;
}
public void setTime(int time)
{
this.time = time;
}
}
TrafficLampComplex tcRed = TrafficLampComplex.RED;
System.out.println(tcRed.nextLamp());
System.out.println(tcRed.getValue());
结果
GREEN
红灯,时长10
三 提示
如果理解该例子有困难,请参看本博客的《jdk1.5新特性5之枚举之模拟枚举类型》