java枚举类型

 

 

Java枚举类型

特定于常量的类主体是 enum 关键字的一个受支持的特性;不过,它们的使用应该受到严格的限制。这个概念正在深入到将枚举类型的每个元素作为一个子类对待的领域。例如,在前面的例子中,Size 枚举类型有一个定价因子参数和 getPricingFactor() 方法。但没有构造函数参数,清单 5 展示了如何利用特定于常量主体来做同样的事。我们添加了一些额外的大小来让这个例子更有趣些。在这里,Small 的定价因子是 0.8,而 ExtraLarge  ExtraExtraLarge 的定价因子是 1.2。其余的大小则采用默认值,即 1.0

 

Constant-specific class bodies

Constant-specific class bodies are a supported feature of the enum keyword; however, their usage should be severely limited. This concept is getting more into the area of treating each element of an enumerated type as a subclass. For instance, in the previous examples, the Size enumerated type had a pricing factor argument and getPricingFactor() method. Instead of having the constructor argument, Listing 5 shows how to do the same thing with a constant-specific body. Some extra sizes are added to make the example a little more interesting. Here, Small has a pricing factor of 0.8, while ExtraLarge and ExtraExtraLarge have a factor of 1.2. The remaining sizes default to a value of 1.0. 

 

public class Sample3 {
  enum Size {
    Small {
      public double getPricingFactor() {
        return 0.8;
      }
    },
    Medium,
    Large,
    ExtraLarge {
      public double getPricingFactor() {
        return 1.2;
      }
    },
    ExtraExtraLarge {
      public double getPricingFactor() {
        return 1.2;
      }
    };
    public double getPricingFactor() {
      return 1.0;
    }

}
  public static void main(String args[]) {
    for (Size s : Size.values()) {
      double d = s.getPricingFactor();
      System.out.println(s + " Size has pricing factor of " + d);
    }
  }
}

  java中可以自己定义枚举类型,该枚举类型中的常量是该枚举类型的实例。枚举常量拥有该枚举类型和继承之java.lang.Enum类中的方法,可以对一些非final的方法进行override。见上例。

 

参考文章:Taming Tiger: Beyond the basics of enumerated types. http://www.ibm.com/developerworks/java/library/j-tiger04195/index.html

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值