成員存取修飾詞定義可見性邊界,是封裝的核心機制。
| 修飾詞 | 可見範圍 | 典型用途 |
|---|---|---|
public | 任何地方 | 對外介面、API |
private | 僅宣告類別內部 | 內部實作細節、預設 |
protected | 宣告類別 + 衍生類別 | 衍生類別需存取的輔助成員 |
internal | 相同組件 | 組件內部協作、單元測試友善 |
class Vehicle {
public int Wheels;
protected float Weight;
public void F() { Wheels=4; Weight=10; } // 自身存取皆合法
}
class Train {
private float Weight; // 自有私有成員
public void F() {
Vehicle v = new Vehicle();
v.Wheels = 4; // ✅ public
// v.Weight = 6; // ❌ protected,外部不可存取
Weight = 6; // ✅ 自有 private
}
}
class Car : Vehicle {
public void F() {
Vehicle v = new Vehicle();
v.Wheels = 4; // ✅ public
v.Weight = 6; // ✅ protected,衍生類別可存取基類 protected
}
}
protected 允許衍生類別存取基類實例的 protected 成員(非僅限 this)。internal 適合組件內單元測試存取內部實作。private。