//定義超類superA class superA { int i = 100; void fun() { System.out.println(“This is superA”); } } //定義superA的子類subB class subB extends superA { int m = 1; void fun() { System.out.println(“This is subB”); } } //定義superA的子類subC class subC extends superA { int n = 1; void fun() { System.out.println(“This is subC”); } }
class Test { public static void main(String[] args) { superA a; subB b = new subB(); subC c = new subC(); a=b; a.fun(); (1) a=c; a.fun(); (2) } }
運行結果為:
This is subB This is subC
上述代碼中subB和subC是超類superA的子類,我們在類Test中聲明了3個引用變量a, b, c,通過將子類對象引用賦值給超類對象引用變量來實現動態方法調用。也許有人會問:“為什么(1)和(2)不輸出:This is superA”。java 的這種機制遵循一個原則:當超類對象引用變量引用子類對象時,被引用對象的類型而不是引用變量的類型決定了調用誰的成員方法,但是這個被調用的方法必須是在超類中定義過的,也就是說被子類覆蓋的方法。