• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

J2SE 5.0实例—枚举

servlet/jsp 搞代码 7年前 (2018-06-18) 137次浏览 已收录 0个评论

枚举
在过去,我们必须用整型常数代替枚举,随着J2SE 5.0的发布,这样的方法终于一去不复返了。

一个简单的枚举类型定义如下:

public enum Weather

http://www.gaodaima.com/40791.htmlJ2SE 5.0实例—枚举

{

     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的改进,代码量的问题应该会被淡化。

欢迎大家阅读《J2SE 5.0实例—枚举》,跪求各位点评,若觉得好的话请收藏本文,by 搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:J2SE 5.0实例—枚举

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址