枚举的使用场景
目录基本定义
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
带属性的枚举
枚举可以拥有字段、方法和构造函数:
public enum Day {
SUNDAY(0), MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6);
private int dayOfWeek;
private Day(int dayOfWeek) {
this.dayOfWeek = dayOfWeek;
}
public int getDayOfWeek() {
return dayOfWeek;
}
}
使用枚举
枚举的使用与类非常相似,你可以像使用类一样使用枚举:
public class Test {
public static void main(String[] args) {
Day day = Day.MONDAY;
System.out.println("Today is " + day);
System.out.println("Day of the week: " + day.getDayOfWeek());
}
}
枚举方法
枚举可以有自己的方法,包括抽象方法:
public enum Operation {
PLUS {
public double apply(double x, double y) { return x + y; }
},
MINUS {
public double apply(double x, double y) { return x - y; }
};
public abstract double apply(double x, double y);
}
枚举与switch语句
枚举常量可以用在switch
语句中:
public class Test {
public static void main(String[] args) {
Day day = Day.MONDAY;
switch (day) {
case MONDAY:
System.out.println("Mondays are tough.");
break;
case FRIDAY:
System.out.println("Fridays are great!");
break;
default:
System.out.println("Midweek.");
break;
}
}
}
枚举迭代
可以使用values()
方法遍历枚举的所有常量:
for (Day day : Day.values()) {
System.out.println(day);
}
枚举与Java反射
枚举支持Java反射API,可以动态地获取枚举信息:
for (Day day : Day.values()) {
String name = day.name();
int ordinal = day.ordinal();
System.out.println("Name: " + name + ", Ordinal: " + ordinal);
}
枚举实现接口
枚举可以实现接口,这使得枚举可以有行为:
public interface Vehicle {
void drive();
}
public enum Car implements Vehicle {
BUS {
@Override
public void drive() {
System.out.println("Driving a bus.");
}
},
CAR {
@Override
public void drive() {
System.out.println("Driving a car.");
}
};
@Override
public abstract void drive();
}
枚举序列化
枚举类型默认实现了Serializable
接口,这意味着枚举常量可以被序列化和反序列化。
枚举类提供了一种强大的方式来组织一组相关的常量,并且可以包含方法和属性,使得它们比传统的枚举更加灵活和强大。
标签:场景,System,public,枚举,使用,println,Day,day From: https://www.cnblogs.com/luoyiwen123/p/18347806