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