物件建立時自動呼叫,用於初始化資料成員與執行特定操作。
new ClassName(args) 呼叫
public class Human {
int height;
// 建構子
public Human(int h) {
this.height = h;
System.out.println("I'm born, height: " + h);
}
public int getHeight() { return height; }
}
public class Test {
public static void main(String[] args) {
Human person = new Human(160); // 呼叫建構子
System.out.println(person.getHeight()); // 160
}
}
輸出:
I'm born, height: 160
160
this.height = h;System.out.println(...)三種初始化方式優先級(高 → 低):
建構子 > 顯式初始化 > 預設初始化
class Human {
int height = 170; // 顯式初始化
public Human(int h) {
this.height = h; // 建構子覆蓋
}
}
Human h = new Human(160);
System.out.println(h.height); // 160(建構子勝出)
| 類型 | 預設值 |
|---|---|
| 數值型 | 0 |
| 布林值 | false |
| 物件參考 | null |
同一類別中定義多個同名方法,參數列表不同(類型、個數、順序)。編譯器根據呼叫時的實參決定呼叫哪個方法。
class Human {
int height;
String name;
// 建構子 1
public Human(int h) {
this.height = h;
System.out.println("建構子1: height=" + h);
}
// 建構子 2
public Human(int h, String n) {
this.height = h;
this.name = n;
System.out.println("建構子2: height=" + h + ", name=" + n);
}
}
Human h1 = new Human(150); // 呼叫建構子1
Human h2 = new Human(150, "NeZha"); // 呼叫建構子2
class Human {
void breath() {
System.out.println("hu...hu...");
}
void breath(int rep) {
for (int i = 0; i < rep; i++) {
System.out.println("lu...lu...");
}
}
}
Human h = new Human();
h.breath(); // 呼叫無參數版本
h.breath(10); // 呼叫有參數版本,輸出 10 行
void test(int i) { System.out.println("int"); }
void test(long l) { System.out.println("long"); }
void test(Integer i) { System.out.println("Integer"); }
test(1); // int(精確匹配)
test(1L); // long
test(new Integer(1)); // Integer
// 陷阱:null 無法確定類型
// test(null); // 編譯錯誤:ambiguous
test((Integer) null); // 需強制轉型
this.field:存取實例欄位(區分同名參數)this.method():呼叫實例方法this(...):建構子鏈呼叫另一個建構子(必須在第一行)this
class Human {
int height;
String name;
int age;
public Human(int height) {
this(height, "Unknown"); // 呼叫兩參數建構子
}
public Human(int height, String name) {
this(height, name, 0); // 呼叫三參數建構子
}
public Human(int height, String name, int age) {
this.height = height;
this.name = name;
this.age = age;
System.out.println("完整初始化: " + height + ", " + name + ", " + age);
}
}
new Human(160); // 完整初始化: 160, Unknown, 0
new Human(160, "Tom"); // 完整初始化: 160, Tom, 0
new Human(160, "Tom", 25); // 完整初始化: 160, Tom, 25
| 概念 | 關鍵點 |
|---|---|
| 建構子 | 同名、無回傳、new 時呼叫、初始化用 |
| 初始化優先級 | 建構子 > 顯式 > 預設 |
| 方法多載 | 同名、不同參數列表、編譯期綁定 |
| this | 實例參考、區分同名、建構子鏈 |
Rectangle 類別,提供 3 個建構子(寬高、寬高顏色、點座標寬高)Calculator 類別,多載 add 方法支援 int、double、int[]、List<Integer>String、ArrayList、Thread 的建構子多載設計