class A { String show(D obj) { return "a and d"; }
String show(A obj) { return "a and a"; } }
class B extends A { String show(A obj) { return "b and a"; }
String show(B obj) { return "b and b"; } }
class C extends B {}
class D extends B {}
A a1 = new A(); A a2 = new B(); B b = new B(); C c = new C(); D d = new D();
| 呼叫 | 參考型別 | 參數靜態型別 | 選擇方法(編譯期) | 實際執行(執行期) | 輸出 |
|---|---|---|---|---|---|
| a1.show(b) | A | B | A.show(A) — B 是 A 的子類 | B 覆寫了 show(A) | b and a |
| a1.show(c) | A | C | A.show(A) — C 是 A 的子類 | B 覆寫了 show(A) | b and a |
| a1.show(d) | A | D | A.show(D) — 精確匹配 | A.show(D) 未被覆寫 | a and d |
| a2.show(b) | A | B | A.show(A) — a2 型別為 A | a2 實為 B,B 覆寫 show(A) | b and a |
| a2.show(c) | A | C | A.show(A) | B 覆寫 show(A) | b and a |
| a2.show(d) | A | D | A.show(D) | A.show(D) 未被覆寫 | a and d |
| b.show(b) | B | B | B.show(B) | B.show(B) | b and b |
| b.show(c) | B | C | B.show(B) — C 是 B 子類 | B.show(B) | b and a |
| b.show(d) | B | D | B.show(B) — D 是 B 子類 | B.show(B) | b and a |
a2 編譯型別為 A,故只能看到 A 的重載集合。參數 b 型別為 B,匹配 A.show(A)。執行期 a2 實為 B,B 覆寫了 show(A),故輸出 b and a。理解「重載靜態、覆寫動態」是掌握 Java 多態的關鍵。