需求映射
- 三檔速度常量:`SLOW=1, MEDIUM=2, FAST=3`
- 屬性:`speed`(int, default SLOW)、`on`(boolean, default false)、`radius`(double)、`color`(String, default "blue")
- 方法:全屬性 getter/setter、無參/全參構造器、`toString()`、`equals(Object)`
標準實現
public class Fan {
// 常量
public static final int SLOW = 1;
public static final int MEDIUM = 2;
public static final int FAST = 3;
// 屬性
private int speed = SLOW;
private boolean on = false;
private double radius = 5.0; // 示例默認值
private String color = "blue";
// 構造器
public Fan() {}
public Fan(int speed, boolean on, double radius, String color) {
this.speed = speed;
this.on = on;
this.radius = radius;
this.color = color;
}
// Getter/Setter (Lombok @Data 可一鍵生成)
public int getSpeed() { return speed; }
public void setSpeed(int speed) { this.speed = speed; }
public boolean isOn() { return on; }
public void setOn(boolean on) { this.on = on; }
public double getRadius() { return radius; }
public void setRadius(double radius) { this.radius = radius; }
public String getColor() { return color; }
public void setColor(String color) { this.color = color; }
// toString
@Override
public String toString() {
return "Fan{" +
"speed=" + speed +
", on=" + on +
", radius=" + radius +
", color='" + color + '\'' +
'}';
}
// equals
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Fan fan = (Fan) o;
return speed == fan.speed &&
on == fan.on &&
Double.compare(fan.radius, radius) == 0 &&
Objects.equals(color, fan.color);
}
@Override
public int hashCode() {
return Objects.hash(speed, on, radius, color);
}
}
測試代碼
public static void main(String[] args) {
Fan f1 = new Fan(Fan.FAST, true, 10, "red");
Fan f2 = new Fan(Fan.FAST, true, 10, "red");
System.out.println(f1); // toString 輸出
System.out.println(f1.equals(f2)); // true
}