请写出并解释这个java程序的输出结果。看了很久都不理解,请大神说详细点!

class Father {
int m = 5;
public Father() {
this.show();
}
void show() {
System.out.println("父");
}
}
class Child1 extends Father {
int m = 10;
void show() {
System.out.println("Child1:"+m);
}
}
class Child2 extends Father {
void show() {
System.out.println("Child2:"+m);
}
}
public class Test {
public static void main(String args[]) {
Father n = new Child1();
Father n1 = new Child2();
}
}

打印Child1:0和Child2:5,当执行Father n = new Child1();的时候会先执行父类Father里面的字段和无参构造函数,而Child1类里面重写了show方法的,所以父类的方法就被覆盖了所以会调用Child1类的show方法,因为Child1类也定义了int m以为覆盖了父类的m,调用show方法还没有执行Child1类所以m是默认值0,所以打印Child1:0,
Father n1 = new Child2();的时候也是一样执行的,因为Child2类中没有定义int m,所以使用的是父类的中变量
温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答
大家正在搜