枚举类型其实是一个有限制的类,很多类的语法都可以用在枚举上面上,例如自定义域、方法、构造方法等。先看下面一个例子:
package custom;
public enum Prefix
{
// These are the values of this enumerated type.
// Each one is followed by constructor arguments in parentheses.
// The values are separated from each other by commas, and the
// list of values is terminated with a semicolon to separate it from
// the class body that follows.
MILLI("m", .001),
CENTI("c", .01),
DECI("d"),
DECA("D", 10.0),
HECTA("h", 100.0),
KILO("k", 1000.0); // Note semicolon
// semicolon
// This is the constructor invoked for each value above.
private Prefix(String abbrev, double multiplier)
{
this.abbrev = abbrev;
this.multiplier = multiplier;
}
//Another constructor
private Prefix(String abbrev)
{
this.abbrev = abbrev;
this.multiplier = .1;
}
// These are the private fields set by the constructor
private String abbrev;
private double multiplier;
// These are accessor methods for the fields. They are instance methods
// of each value of the enumerated type.
public String abbrev()
{
return abbrev;
}
public double multiplier()
{
return multiplier;
}
}
需注意,一个枚举类型可以有多个构造器。