J2SE 5.0執行個體---枚舉
來源:互聯網
上載者:User
j2se 枚舉
在過去,我們必須用整型常數代替枚舉,隨著J2SE 5.0的發布,這樣的方法終於一去不複返了。
一個簡單的枚舉類型定義如下:
public enum Weather
{
SUNNY,RAINY,CLOUDY
}
枚舉可以用在switch語句中:
Weather weather=Weather.CLOUDY;
switch(weather)
{
case SUNNY:
System.out.println("It's sunny");
break;
case CLOUDY:
System.out.println("It's cloudy");
break;
case RAINY:
System.out.println("It's rainy");
break;
}
枚舉類型可以有自己的構造方法,不過必須是私人的,也可以有其他方法的定義,如下面的代碼:
public enum Weather {
SUNNY("It is sunny"),
RAINY("It is rainy"),
CLOUDY("It is cloudy");
private String description;
private Weather(String description) {
this.description=description;
}
public String description() {
return this.description;
}
}
下面一段代碼是對這個枚舉的一個使用:
for(Weather w:Weather.values())
{
System.out.printf( "Description of %s is \"%s\".\n",w,w.description());
}
Weather weather=Weather.SUNNY;
System.out.println(weather.description() + " today");
如果我們有一個枚舉類型,表示四則運算,我們希望在其中定義一個方法,針對不同的值做不同的運算,那麼我們可以這樣定義:
public enum Operation {
PLUS, MINUS, TIMES, DIVIDE;
// Do arithmetic op represented by this constant
double eval(double x, double y){
switch(this) {
case PLUS: return x + y;
case MINUS: return x - y;
case TIMES: return x * y;
case DIVIDE: return x / y;
}
throw new AssertionError("Unknown op: " + this);
}
}
這樣寫的問題是你如果沒有最後一行拋出異常的語句,編譯就無法通過。而且如果我們想要添加一個新的運算,就必須時刻記著要在eval中添加對應的操作,萬一忘記的話就會拋出異常。
J2SE 5.0提供瞭解決這個問題的辦法,就是你可以把eval函式宣告為abstract,然後為每個值寫不同的實現,如下所示:
public enum Operation {
PLUS { double eval(double x, double y) { return x + y; } },
MINUS { double eval(double x, double y) { return x - y; } },
TIMES { double eval(double x, double y) { return x * y; } },
DIVIDE { double eval(double x, double y) { return x / y; } };
abstract double eval(double x, double y);
}
這樣就避免了上面所說的兩個問題,不過代碼量增加了一些,但是隨著今後各種Java開發 IDE的改進,代碼量的問題應該會被淡化。