Given:



class Base {

    public void test() {
        System.out.println("Base ");
    }
}
class DerivedA extends Base {

    public void test() {
        System.out.println("DerivedA");
    }
}
class DerivedB extends Base {

    public void test() {
        System.out.println("DerivedB");
    }

    public static void main() {
        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

B.

Base
DerivedB

C.

DerivedB
DerivedB

D.

DerivedB
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方法。