Java Enumeration (枚举类型) (3) -- 自定义类体(class body)

本文通过实例详细介绍了枚举类型的高级用法,包括如何自定义枚举类型中的构造方法、域及方法等,并展示了如何利用这些特性来实现更加灵活和强大的枚举类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

枚举类型其实是一个有限制的类,很多类的语法都可以用在枚举上面上,例如自定义域、方法、构造方法等。先看下面一个例子:
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;
    }
}
需注意,一个枚举类型可以有多个构造器。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值