幻境 We are extremely fortunate not to know precisely the kind of world we live in

# 枚举

 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); }

posted on 2005-05-12 10:57 阅读(1100) 评论(0)  编辑  收藏 所属分类: 编程相关

 只有注册用户登录后才能发表评论。 网站导航: 相关文章: