枚舉
在過去,我們必須用整型常數代替枚舉,隨著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的改進,代碼量的問題應該會被淡化。
posted on 2005-05-12 10:57
幻 閱讀(1190)
評論(0) 編輯 收藏 所屬分類:
編程相關