Given:
class Base {
public void test() {
System.out.println("Base ");
}
}
class DerivedA extends Base {
public void test() {
System.out.println("DerivedA");
}
}
class DerivedB extends DerivedA {
public void test() {
System.out.println("DerivedB");
}
public static void main(String[] args) {
Base b1 = new DerivedB();
Base b2 = new DerivedA();
Base b3 = new DerivedB();
b1 = (Base) b3;
Base b4 = (DerivedA) b3;
b1.test();
b4.test();
}
}
What is the result?
A.
Base
DerivedA
DerivedA
B.
Base
DerivedB
DerivedB
C.
DerivedB
DerivedB
DerivedB
D.
DerivedB
DerivedA
DerivedA
E. A classcast Except ion is thrown at runtime.
題解
「DerivedB.java」檔案的 main 方法中的 b1、b3 和 b4 這三個變數在第 12 行執行結束後,所參考到的物件實體都是從 DerivedB 類別實體化出來的第二個物件。Base 類別的 test 方法在 DerivedB 類別中被覆寫,因此「DerivedB.java」檔案中的第 13~14 行程式會去執行第 3 行的 test 方法。
