六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 29|回复: 0

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

[复制链接]

升级  36%

30

主题

30

主题

30

主题

秀才

Rank: 2

积分
104
 楼主| 发表于 2013-1-27 05:19:20 | 显示全部楼层 |阅读模式
枚举类型其实是一个有限制的类,很多类的语法都可以用在枚举上面上,例如自定义域、方法、构造方法等。先看下面一个例子:<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;
    }
}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表