Java 允許類別定義多個建構子(建構函數),只要參數列表不同(參數個數、類型、順序任一差異即可),這稱為建構子重載。
public class Example {
// 無參建構子
public Example() { ... }
// 單參建構子
public Example(String name) { ... }
// 多參建構子
public Example(String name, int age) { ... }
// 參數順序不同也構成重載
public Example(int age, String name) { ... }
}
this(...) 呼叫同類其他建構子,需置於首行建構子重載用於提供多種物件初始化方式。參數過多時考慮建構者模式(Builder Pattern)提升可讀性。