基于 SCJP(EXAM 310-065) 课程的疑问
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 ");
}
House(String name){
this();
System.out.print("hn "+name);
}
public static void main(String[] args){
new House("x ");
}
}
我认为输出必须是b bn h hn x。但输出是bh hn x。
我很困惑。这个输出是怎么来的。帮我
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 ");
}
House(String name){
this();
System.out.print("hn "+name);
}
public static void main(String[] args){
new House("x ");
}
}
I THOUGHT THE OUTPUT MUST BE b bn h hn x. But the output is b h hn x.
I'm confused. How this output comes. Help me
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能会想到 Java 插入到构造函数中的对
super()
的隐式调用。但请记住,Java 仅在需要时才执行此操作 - 也就是说,当您自己不调用另一个构造函数时。当您在单参数House
构造函数中调用this()
时,您已经推迟到另一个构造函数,因此 Java 不会插入对super 的调用()
那里。相反,在零参数构造函数
House()
中,您不会通过调用this(...)
或super 来启动它(...)
。因此,在该函数中,Java 会为您插入super()
。最重要的是,Java 从不调用
Building(String)
。在对象初始化期间,仅调用一个超类构造函数,而且它是不带参数的构造函数。You're probably thinking of the implicit call to
super()
that Java inserts into constructors. But remember that Java only does this when it needs to - that is, when you don't invoke another constructor yourself. When you callthis()
in the one-argumentHouse
constructor, you're already deferring to another constructor, so Java doesn't insert the call tosuper()
there.In contrast, in the zero-argument constructor
House()
, you don't start it out with a call to eitherthis(...)
orsuper(...)
. So in that one, Java does insert thesuper()
for you.Bottom line, Java never calls
Building(String)
. Only one superclass constructor gets called during the initialization of the object, and it's the one with no arguments.构造函数调用链的顺序是:
1. 房屋(字符串名称)
2. 房子()
3. Building()
产生输出
bh hn
后跟 printf 语句。 x 产生最终输出 **bh hn x **
这是因为;
1. House(String name)中显式调用了构造函数this()。这避免了对 Java 插入的 super() 的隐式调用。
2. 构造函数 House() 中没有显式构造函数调用,导致 Java 插入对其超类构造函数 Building() 的隐式调用。这会在 House() 中的 printf 语句 **h ** 之前打印 **b **。
The order of constructor call chain is:
1. House(String name)
2. House()
3. Building()
producing output
b h hn
followed by the printf statement. x resulting in final output **b h hn x **
This is because;
1. There is an explicit call to constructor this() in House(String name). This avoids the implicit call to super() which Java inserts.
2. There is no explicit constructor call in constructor House() resulting Java to insert an implicit call to its super class constructor Building(). This prints **b ** before the printf statement **h ** in House().