jefflee 发表于 2013-1-27 05:19:20

Java Enumeration (枚举类型) (3) -

枚举类型其实是一个有限制的类,很多类的语法都可以用在枚举上面上,例如自定义域、方法、构造方法等。先看下面一个例子:<div style="border: 1px solid rgb(204, 204, 204); padding: 4px 5px 4px 4px; background-color: rgb(238, 238, 238); font-size: 13px; width: 98%;"><!---->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;
    }
}
页: [1]
查看完整版本: Java Enumeration (枚举类型) (3) -