J2SE 5.0实例---枚举
2005-03-18 12:48
477 查看
枚举
在过去,我们必须用整型常数代替枚举,随着J2SE 5.0的发布,这样的方法终于一去不复返了。一个简单的枚举类型定义如下:
public enum Weather{ SUNNY,RAINY,CLOUDY } |
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); } } |
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); } |
相关文章推荐
- Eclipse3.1中体验J2SE 5.0之枚举类型
- J2SE5.0 实例---泛型
- J2SE5.0新特性之枚举类型
- J2SE5.0新特性之枚举类型
- J2SE 5.0实例---原生类型的autoboxing和auto-unboxing
- J2SE 5.0新特性(一)枚举
- J2SE5.0 实例---变长参数
- [J2SE 5.0专题]类型安全的枚举
- [J2SE 5.0专题][2.4]类型安全的枚举
- J2SE 5.0实例---静态引入
- Eclipse3.1中体验J2SE 5.0之枚举类型!
- J2SE5.0新特性之枚举类型
- J2SE5.0 实例---循环语句的增强
- J2SE5.0实例---注释(annotation)
- J2SE 5.0新特性(一)枚举
- J2SE5.0新特性之枚举类型
- Eclipse3.1中体验J2SE 5.0之枚举类型
- J2SE(TM) 5.0 语言特性
- C#中的枚举及相关实例
- J2SE基础夯实系列之JDBC,链接数据库实例代码