Given the class definitions:

class Alpha {
    public String doStuff(String msg) {
        return msg;
    }
}

class Beta extends Alpha {
    public String doStuff(String msg) {
        return msg.replace('a', 'e');
    }
}

class Gamma extends Beta {
    public String doStuff(String msg) {
        return msg.substring(2);
    }
}

And the code fragment of the main() method,

List<Alpha> strs = new ArrayList<Alpha>();
strs.add(new Alpha());
strs.add(new Beta());
strs.add(new Gamma());
for (Alpha t : strs) {
    System.out.println(t.doStuff("Java"));
}

What is the result?

A.

Java
Java
Java

B.

Java
Jeve
va

C.

Java
Jeve
ve

D. Compilation fails

题解

由于「doStuff」是对象方法,因此会发生覆写(Override)的作用。不管对象如何向上转型,都需从它的实体对象的所属类别型态开始向上寻找最后发生覆写的方法。在这个题目中,「Alpha」、「Beta」、「Gamma」都有覆写「doStuff」对象方法,所以它们的实体对象都会使用到自己的「doStuff」对象方法。因此输出结果为:

Java
Jeve
va