首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java 風扇類設計:屬性封裝、構造器重載、toString/equals 重寫完整示例

     編輯:程式設計綜合問答

需求映射

  • 三檔速度常量:`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
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved