【发布时间】:2012-12-19 16:56:11
【问题描述】:
我的程序
class Building {
Building() {
System.out.print("b ");
}
Building(String name) {
this();
System.out.print("bn " + name);
}
};
public class House extends Building {
House() {
System.out.print("h "); // this is line# 1
}
House(String name) {
this(); // This is line#2
System.out.print("hn " + name);
}
public static void main(String[] args) {
new House("x ");
}
}
我们知道编译器将调用super() 作为子类构造函数的第一行。因此输出不应该是:
b(从编译器调用 super(),在第 2 行之前)
b(再次来自编译器对 super() 的调用,在第 1 行之前)
h hn x
但是输出是
b h hn x
这是为什么呢?
【问题讨论】:
-
House(x) -> this() (House()) -> Building ()
-
如果
super()构造函数被多次调用也没有多大意义——这也可能违反了Java 的构造函数契约。