java枚举类写法

在Java中,枚举类型是一种特殊的类,用于表示固定数量的常量。枚举类型在Java 5之后引入。以下是一些Java枚举类的示例代码:

**例1:**基本的枚举类

 
public enum Day { 
SUNDAY, 
MONDAY, 
TUESDAY, 
WEDNESDAY, 
THURSDAY, 
FRIDAY, 
SATURDAY
//使用案例
public class EnumExample {  
    public static void main(String[] args) {  
        Day day = Day.MONDAY;  
        switch (day) {  
            case MONDAY:  
                System.out.println("It's Monday!");  
                break;  
            case TUESDAY:  
                System.out.println("It's Tuesday!");  
                break;  
            // 其他天数的情况...  
            default:  
                System.out.println("It's some other day.");  
        }  
    }   
}


在这个例子中,我们定义了一个名为 Day 的枚举类型,它具有7个可能的值,表示一周中的每一天。每个值都是大写的,这是Java枚举常量的常见约定。

**例2:**包含构造函数的枚举类

public enum Planet { 
MERCURY(3.303e+23, 2.4397e6), 
VENUS(4.869e+24, 6.0518e6), 
EARTH(5.976e+24, 6.37814e6), 
MARS(6.421e+23, 3.3972e6); 


private final double mass; // in kilograms 
private final double radius; // in meters 


// constructor 
Planet(double mass, double radius) { 
this.mass = mass; 
this.radius = radius; 
} 


public double getMass() { return mass; } 
public double getRadius() { return radius; } 
}
public class EnumExample {  
    public static void main(String[] args) {  
        Planet planet = Planet.EARTH;  
        System.out.println("The mass of " + planet + " is " + planet.getMass() + " kilograms.");  
        System.out.println("The radius of " + planet + " is " + planet.getRadius() + " meters.");  
    }  
}


在这个例子中,我们定义了一个名为 Planet 的枚举类型,它具有4个可能的值,表示太阳系中的4个行星。每个行星都有一个质量和半径,这些值在创建枚举常量时通过构造函数设置。我们还为每个行星添加了一个获取质量和半径的方法。

**例3:**包含方法的枚举类

public enum Operation { 
PLUS { 
public int apply(int x, int y) { return x + y; } 
}, 
MINUS { 
public int apply(int x, int y) { return x - y; } 
}, 
TIMES { 
public int apply(int x, int y) { return x * y; } 
}, 
DIVIDE { 
public int apply(int x, int y) { return x / y; } 
}; 


public abstract int apply(int x, int y); 
}
//示例
public class EnumExample {  
    public static void main(String[] args) {  
        Operation operation = Operation.PLUS;  
        int result = operation.apply(5, 3);  
        System.out.println("5 " + operation + " 3 = " + result);  
    }  
}

 

在这个例子中,我们定义了一个名为 Operation 的枚举类型,它具有4个可能的值,表示4种基本的数学运算。每种运算都是一个方法,这些方法在创建枚举常量时通过匿名类实现。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值