【发布时间】:2012-03-28 09:43:28
【问题描述】:
代码如下,我定义了父子两个类,并在主函数中创建:
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
但我不明白这是怎么发生的?谁能告诉我为什么?
【问题讨论】:
-
经验教训:不要从可以被覆盖的构造函数中调用方法。
-
另一个要吸取的教训是,您应该始终尝试提出不能被误解的“调试”消息:我会将您的方法更改为
System.out.println("Son.who()");、System.out.println("Son.tell(" + name + ")");,System.out.println("Father.who()");和System.out.println("Father.tell(" + name + ")");
标签: java