class A { public int f() { System.out.println("call A.f()"); return 1; } }
class B extends A { public int f() { System.out.println("call B.f()"); return 2; } }
class C extends B { public int f() { System.out.println("call C.f()"); return 3; } }
public class Test01 {
public static void main(String args[]) {
C c = new C();
System.out.println(((A)c).f()); // 輸出 call C.f() 而非 call A.f()
}
}
Java 方法調用採用動態繫結:編譯期看引用型別(A),執行期看實際物件型別(C)。強制轉型 (A)c 僅改變引用的靜態型別,不改變物件在堆上的實際型別。因此 JVM 依然根據物件真實類型 C 分派到 C.f()。
super.f() 呼叫(僅限直接父類)。A a = new A(); a.f();。