这是代码,我定义了两个名为“父亲”和“儿子”的类,并在主函数中创建它们:
public class Test {
public static void main(String[] args) {
Father father = new Son();
}
}
class Father {
private String name = "father";
public Father() {
who();
tell(name);
}
public void who() {
System.out.println("this is father");
}
public void tell(String name) {
System.out.println("this is " + name);
}
}
class Son extends Father {
private String name = "son";
public Son() {
who();
tell(name);
}
public void who() {
System.out.println("this is son");
}
public void tell(String name) {
System.out.println("this is " + name);
}
}
我得到这样的输出:
this is son
this is father
this is son
this is son
但是我不明白这是怎么发生的?谁能告诉我为什么?
最佳答案
Son
的构造函数开始。public Son() {
super(); // implied
who();
tell(name);
}
public Father() {
who();
tell(name);
}
who()
覆盖了Son
,所以将调用Son
的版本,并打印“this is son”。 tell()
也将被覆盖,但传入的值为Father.name
,显示“this is父亲”。 who()
的构造函数中的tell(name)
和Son
调用分别打印“this is son”和“this is son”。