建構子是特殊方法,名稱與類別相同、無回傳型別,在 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(...) 避免重複程式碼。