什麼是封裝?
封裝是將類的屬性私有化(private),對外僅暴露公共的存取方法(Getter/Setter),從而控制資料的讀寫邏輯,實現資訊隱藏與存取控制。
為什麼需要封裝?
- 資料驗證:Setter 中可加入合法性檢查(如年齡 > 0)。
- 維護性:內部實現變更(如改用 Map 儲存)不影響呼叫端。
- 安全性:防止外部直接修改關鍵狀態導致不一致。
標準封裝範本
public class Person {
private String name; // 私有屬性
private int age;
// Getter
public String getName() { return name; }
public int getAge() { return age; }
// Setter(含驗證)
public void setName(String name) { this.name = name; }
public void setAge(int age) {
if (age > 0 && age < 150) this.age = age;
else throw new IllegalArgumentException("年齡不合法");
}
}
this 關鍵字詳解
- 代表當前物件的引用,僅能在非靜態上下文使用。
- 解決區域變數遮蔽成員變數:
this.name = name;
- 構造方法間互調:
this(name, 18);(必須放首行)。
構造方法:物件初始化的守門員
語法規則
- 方法名與類名完全一致。
- 無返回類型(連
void 都不能寫)。
new Class() 觸發調用。
為什麼需要構造方法?
避免「忘記設值」導致物件處於不完整狀態。構造方法強制在創建時完成必要初始化。
帶參構造方法(多態初始化)
public Person(String name) { this.name = name; }
public Person(String name, int age) { this(name); this.age = age; } // 串聯調用
方法重載 vs 構造方法重載
| 特性 | 方法重載 | 構造方法重載 |
| 判斷依據 | 參數列表(類型、個數、順序) | 同左 |
| 返回類型 | 無關 | 無返回類型 |
| 典型案例 | System.out.println() 多態 | 不同參數創建不同初始狀態物件 |
完整實戰範例
public class Student {
private String id;
private String name;
private char gender;
public Student() {} // 無參構造
public Student(String id, String name) { // 兩參構造
this.id = id; this.name = name;
}
public Student(String id, String name, char gender) { // 三參構造
this(id, name); this.gender = gender; // 串聯
}
// Getter/Setter 省略
public void print() { System.out.println(id + " " + name + " " + gender); }
}
// 使用
new Student("1", "Alice").print();
new Student("2", "Bob", 'M').print();
總結
封裝 = private 屬性 + 公共 Getter/Setter + 構造方法初始化。善用 this 消除歧義,透過重載提供多樣化的建構方式,是寫出健壯、可維護 Java 代碼的基石。
- 上一篇文章: JSP 自定義標籤庫(Taglib)實戰:TagSupport、SimpleTagSupport、BodyTagSupport 三大體系完整案例
- 下一篇文章: Java 基礎必會:基本類型與包裝類、字串互轉完整指南(含自動裝箱/拆箱)
Copyright ©
程式碼之家 All Rights Reserved