天天看點

jdk1.5新特性5之枚舉之枚舉類型的應用

一 簡單應用

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之枚舉之模拟枚舉類型》

繼續閱讀