温馨提示×

java枚举类型怎样实现功能

小樊
81
2024-11-19 14:40:47
栏目: 编程语言

Java 枚举类型(Enum)是一种特殊的类,用于表示固定数量的常量值。枚举类型可以实现一些功能,例如:

  1. 定义一组有限的常量值:
public enum Weekday {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
  1. 为枚举类型添加方法和属性:
public enum Weekday {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;

    private int dayNumber;

    public Weekday(int dayNumber) {
        this.dayNumber = dayNumber;
    }

    public int getDayNumber() {
        return dayNumber;
    }

    public void setDayNumber(int dayNumber) {
        this.dayNumber = dayNumber;
    }

    public String getDayOfWeek() {
        switch (this) {
            case MONDAY:
                return "Monday";
            case TUESDAY:
                return "Tuesday";
            case WEDNESDAY:
                return "Wednesday";
            case THURSDAY:
                return "Thursday";
            case FRIDAY:
                return "Friday";
            case SATURDAY:
                return "Saturday";
            case SUNDAY:
                return "Sunday";
            default:
                throw new IllegalStateException("Unknown day: " + this);
        }
    }
}
  1. 使用枚举类型:
public class EnumExample {
    public static void main(String[] args) {
        Weekday today = Weekday.FRIDAY;
        System.out.println("Today is " + today.getDayOfWeek());
        System.out.println("Day number: " + today.getDayNumber());

        today = Weekday.WEDNESDAY;
        System.out.println("Today is " + today.getDayOfWeek());
        System.out.println("Day number: " + today.getDayNumber());
    }
}

在这个例子中,我们定义了一个名为 Weekday 的枚举类型,它表示一周的七天。我们还为这个枚举类型添加了一个构造函数、一个 getDayNumber() 方法和一个 getDayOfWeek() 方法。然后,在 EnumExample 类的 main 方法中,我们使用了这个枚举类型来表示今天是星期几以及它是星期几的数字。

0