// Java Enum 高级用法示例
// 1. 枚举类中添加构造函数和成员变量
public enum Color {
RED(255, 0, 0),
GREEN(0, 255, 0),
BLUE(0, 0, 255);
private final int r;
private final int g;
private final int b;
// 构造函数
Color(int r, int g, int b) {
this.r = r;
this.g = g;
this.b = b;
}
// 获取RGB值的方法
public int getRed() { return r; }
public int getGreen() { return g; }
public int getBlue() { return b; }
@Override
public String toString() {
return "RGB(" + r + ", " + g + ", " + b + ")";
}
}
// 2. 枚举类中添加抽象方法,并在枚举实例中实现
public enum Operation {
PLUS {
@Override
public double apply(double x, double y) {
return x + y;
}
},
MINUS {
@Override
public double apply(double x, double y) {
return x - y;
}
},
TIMES {
@Override
public double apply(double x, double y) {
return x * y;
}
},
DIVIDE {
@Override
public double apply(double x, double y) {
if (y == 0) throw new ArithmeticException("Cannot divide by zero");
return x / y;
}
};
// 抽象方法
public abstract double apply(double x, double y);
}
// 3. 枚举类中使用静态方法和静态块
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),
JUPITER(1.9e+27, 7.1492e7),
SATURN(5.688e+26, 6.0268e7),
URANUS(8.686e+25, 2.5559e7),
NEPTUNE(1.024e+26, 2.4746e7);
private static final double G = 6.67300E-11;
private final double mass; // in kilograms
private final double radius; // in meters
// Static block to initialize some common values
static {
System.out.println("Initializing Planets...");
}
// Constructor
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
// Method to calculate surface gravity
private double surfaceGravity() {
return G * mass / (radius * radius);
}
// Method to calculate surface weight
public double surfaceWeight(double otherMass) {
return otherMass * surfaceGravity();
}
// Static method to find a planet by name
public static Planet getPlanetByName(String name) {
for (Planet p : Planet.values()) {
if (p.name().equalsIgnoreCase(name)) {
return p;
}
}
return null;
}
}
枚举类中添加构造函数和成员变量:
Color 枚举类包含 RGB 值的成员变量,并通过构造函数初始化。toString 方法,方便打印。枚举类中添加抽象方法,并在枚举实例中实现:
Operation 枚举类定义了一个抽象方法 apply,每个枚举实例实现了该方法。枚举类中使用静态方法和静态块:
Planet 枚举类包含静态常量、构造函数、静态块、静态方法和实例方法。上一篇:java获取近七天日期
下一篇:java线程同步
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站