Doubt based on program in 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 st开发者_运维知识库atic 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
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 call this()
in the one-argument House
constructor, you're already deferring to another constructor, so Java doesn't insert the call to super()
there.
In contrast, in the zero-argument constructor House()
, you don't start it out with a call to either this(...)
or super(...)
. So in that one, Java does insert the super()
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.
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().
精彩评论