Java 中枚举(enum)是一种特殊的类,用于表示一组固定的常量。枚举类型使得代码更加清晰、类型安全,并且易于维护。
基本用法:
定义枚举:
public enum Day {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
示例:
public class EnumExample {
public static void main(String[] args) {
Day today = Day.WEDNESDAY;
switch (today) {
case MONDAY:
System.out.println("Today is Monday.");
break;
case WEDNESDAY:
System.out.println("Today is Wednesday.");
break;
// 其他 case 语句
default:
System.out.println("Today is another day.");
break;
}
}
枚举中方法和构造函数
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; }
// 示例方法:计算表面重力
public double surfaceGravity() {
final double G = 6.67300E-11;
return G * mass / (radius * radius);
}
public static void main(String[] args) {
double earthGravity = EARTH.surfaceGravity();
System.out.println("Earth's surface gravity is " + earthGravity + " m/s^2");
}
}
枚举的迭代
enum Color
{
RED, GREEN, BLUE;
}
public class MyClass {
public static void main(String[] args) {
for (Color myVar : Color.values()) {
System.out.println(myVar);
}
}
}
标签:Java,double,学习,枚举,radius,println,mass,public From: https://blog.csdn.net/xuann/article/details/144122770