假定Base b = new Derived(); 调用执行b.methodOne()后,输出结果是什么?
public class Base {
public void methodOne() {
System.out.print("A");
methodTwo(); //line 1
}
public void methodTwo() {
System.out.print("B");
}
}
public class Derived extends Base {
public void methodOne() {
super.methodOne();
System.out.print("C");
}
public void methodTwo() {
super.methodTwo(); // line 2
System.out.print("D");
}
}
public class Test {
public static void main(String[] args) {
Base b = new Derived();
b.methodOne();
}
}
A. ABDC
B. AB
C. ABCD
D. ABC
正确答案A
解析:
如果new的是子类的对象,没有显式调用父类方法的话,子类重写了父类的方法则执行子类的方法。
如果用super显式调用父类的方法则执行父类的方法。
将本题line 1替换成抽象方法即模板模式