問題提到 super 和 supply。Java/Android 中沒有 supply 關鍵字,推測為輸入法誤觸或聽錯。本文針對 super 詳細說明。
class Parent {
String name = "Parent";
void show() { System.out.println("Parent show"); }
}
class Child extends Parent {
String name = "Child";
void print() {
System.out.println(name); // Child
System.out.println(super.name); // Parent ← 存取父類被遮蔽的變數
}
@Override
void show() {
super.show(); // 呼叫父類實作
System.out.println("Child show");
}
}
class Parent {
Parent(String msg) { System.out.println(msg); }
}
class Child extends Parent {
Child() {
super("Hello from Child"); // 顯式呼叫父類帶參建構子
// 若無 super(...),編譯器隱含插入 super() (呼叫無參建構子)
}
}
| 關鍵字 | 指向 | 主要用途 |
|---|---|---|
this | 當前類實例 | 區分同名成員、建構子鏈、傳遞自身引用 |
super | 父類實例 (同一物件的父類部分) | 存取被覆寫/遮蔽的父類成員、呼叫父類建構子 |
super / this → 編譯錯誤。this(...) 和 super(...) → 編譯錯誤,二擇一且必須首行。super 能存取父類 private 成員 → 不能,需父類提供 protected/public 存取器。