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

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