class People { public String getName() { return "people"; } }
class Student extends People { public String getName() { return "student"; } }
People pp = new Student();
System.out.println(pp.getName()); // 輸出 "student" ✅
class People { protected String name = "people"; }
class Student extends People { protected String name = "student"; }
People pp = new Student();
System.out.println(pp.name); // 輸出 "people" ❌(父類別欄位)
pp 編譯型別為 People,故存取 name 綁定父類別欄位。
class People {
protected String name = "people";
public String getName() { return name; }
}
class Student extends People {
protected String name = "student";
public String getName() { return name; } // 覆寫
}
People pp = new Student();
System.out.println(pp.getName()); // 輸出 "student" ✅
此時 getName() 動態分派至 Student,方法內 this.name 解析為子類別欄位,達到預期多型效果。
| 特性 | 方法覆寫 | 變數遮蔽 |
|---|---|---|
| 綁定時機 | 執行期(動態) | 編譯期(靜態) |
| 依據 | 實際物件型別 | 參考變數宣告型別 |
| 多型支援 | 是 | 否 |
| 存取修飾詞限制 | 不可縮小(public→protected ❌) | 無限制,甚至可改型別 |
| @Override 註解 | 建議加上,編譯器檢查 | 不適用 |