views:

68

answers:

2
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

+2  A: 

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.

David Zaslavsky
How can we call 'Building(String name)' constructor from the House class?
zengr
You can call `Building(String)` from `House(String)` by making the first line of `House(String name)` be `super(name)`. This would have to replace the call to `this()`.
David Zaslavsky
A: 

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().

Tushar Tarkas