Java中的枚举(Enum)详解与案例
枚举(Enum)是Java中的一种特殊数据类型,它允许程序员定义变量为一组预定义的常量。枚举在Java中被广泛使用,特别是在需要表示一组固定常量时,如星期几、月份、颜色等。
1. 枚举的基本用法
定义一个简单的枚举类型:
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
使用枚举类型:
public class EnumExample {
public static void main(String[] args) {
Day today = Day.MONDAY;
System.out.println("Today is: " + today);
}
}
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
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
public double mass() { return mass; }
public double radius() { return radius; }
// Universal gravitational constant (m3 kg-1 s-2)
public static final double G = 6.67300E-11;
// Calculate surface gravity
double surfaceGravity() {
return G * mass / (radius * radius);
}
double surfaceWeight(double otherMass) {
// F = ma
return otherMass * surfaceGravity();
}
public static void main(String[] args) {
double earthWeight = 175;
double mass = earthWeight / EARTH.surfaceGravity();
for (Planet p : Planet.values()) {
System.out.printf("Your weight on %s is %f%n",
p, p.surfaceWeight(mass));
}
}
}
3. 枚举中的构造器必须是私有的
枚举的构造器默认是私有的,这意味着你不能从枚举类外部创建枚举实例。这也是枚举的一种保护机制,防止枚举常量被外部恶意修改。
4. 枚举中的方法重载和覆写
枚举可以覆盖`toString`方法,用于返回枚举常量的字符串表示。
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; }
},
TIMES {
public double apply(double x, double y) { return x * y; }
},
DIVIDE {
public double apply(double x, double y) { return x / y; }
};
public abstract double apply(double x, double y);
}
5. 枚举在switch语句中的应用
枚举非常适合在switch语句中使用,因为它们的常量是有限的,这使得代码更加清晰和易于维护。
public class EnumSwitchExample {
public static void main(String[] args) {
Day day = Day.WEDNESDAY;
switch (day) {
case MONDAY:
System.out.println("Today is Monday");
break;
case TUESDAY:
System.out.println("Today is Tuesday");
break;
case WEDNESDAY:
System.out.println("Today is Wednesday");
break;
case THURSDAY:
System.out.println("Today is Thursday");
break;
case FRIDAY:
System.out.println("Today is Friday");
break;
case SATURDAY:
System.out.println("Today is Saturday");
break;
case SUNDAY:
System.out.println("Today is Sunday");
break;
}
}
}
总结
通过本文的详细讲解和案例,希望你已经对Java中的枚举有了更深入的理解。枚举在Java中是一个非常有用的数据类型,它不仅可以提高代码的可读性和可维护性,还可以保证类型安全。