写出下面代码的输出结果。
class A {
public static void hello() {
System.out.println("A");
}
private void showMsg() {
System.out.println("This is A");
}
public void show() {
showMsg();
}
}
public class B extends A {
public static void hello() {
System.out.println("B");
}
private void showMsg() {
System.out.println("This is B");
}
public static void main(String[] args) {
A a = new B();
a.show();
a.hello();
}
}
参考答案
This is A
A
解析:a.show() 由多态特性,执行的是子类B中的show方法,子类B中没有定义show方法,使用的是从父类A中继承的show();接下来show()内部调用了showMsg(),这个方法是私有的,不存在方法重写,因此调用的是父类自己的showMsg(),最终打印This is A
hello方法为静态方法,静态方法没有重写的特性,调用哪个静态方法是看引用类型,而不是看被引用的对象,因此最终打印A