枚举
在过去,我们必须用整型常数代替枚举,随着j2se 5.0的发布,这样的方法终于一去不复返了。
一个简单的枚举类型定义如下:
public enum weather
{
sunny,rainy,cloudy
}
枚举可以用在switch语句中:
weather weather=weather.cloudy;
switch(weather)
{
case sunny:
system.out.println("its sunny");
break;
case cloudy:
system.out.println("its cloudy");
break;
case rainy:
system.out.println("its 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的改进,代码量的问题应该会被淡化。
