首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 建構子詳解:從無參到帶參數的物件初始化最佳實踐

     編輯:Java 相關知識

什麼是建構子?

建構子是特殊方法,名稱與類別相同、無回傳型別,在 new 物件時自動執行,用於初始化欄位。

未使用建構子的缺點

Car c = new Car();
c.color = "red";
c.brand = "xxx";
// 欄位多時逐一指派極易遺漏、維護困難

帶參數建構子的優勢

class Car {
    String color, brand;
    public Car(String color, String brand) {
        this.color = color;   // this 區分欄位與參數
        this.brand = brand;
    }
    void show() { System.out.printf("顏色:%s, 品牌:%s%n", color, brand); }
}

public class Demo {
    public static void main(String[] args) {
        Car c = new Car("red", "Tesla"); // 一次完成初始化
        c.show();
    }
}

進階:建構子鏈結

class Car {
    String color, brand; int year;
    public Car(String color, String brand) { this(color, brand, 2024); }
    public Car(String color, String brand, int year) {
        this.color = color; this.brand = brand; this.year = year;
    }
}

重點整理

  • 建構子可多載,提供多種初始化方式。
  • 若未自訂建構子,編譯器會產生預設無參建構子;一旦自訂,預設即消失。
  • 善用 this(...) 避免重複程式碼。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved