一 简单应用
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
yellow
green
二 复杂应用
public enum trafficlampcomplex
// 元素列表必须放在枚举类的最上面
red(10)
{
@override
public trafficlampcomplex nextlamp()
{
return green;
}
public string getvalue()
return "红灯,时长" + this.gettime();
},
green(10)
return yellow;
return "绿灯,时长" + this.gettime();
yellow(5)
return "黄灯,时长" + this.gettime();
};
/**
* 时长
*/
private int time;
trafficlampcomplex()
}
trafficlampcomplex(int time)
this.time = time;
* 下一个灯
* @return
public abstract trafficlampcomplex nextlamp();
* 取值
public abstract string getvalue();
public int gettime()
return time;
public void settime(int time)
trafficlampcomplex tcred = trafficlampcomplex.red;
system.out.println(tcred.nextlamp());
system.out.println(tcred.getvalue());
红灯,时长10
三 提示
如果理解该例子有困难,请参看本博客的《jdk1.5新特性5之枚举之模拟枚举类型》