Home > OS >  Why does super() not get called in the other constuctor?
Why does super() not get called in the other constuctor?

Time:06-11

If both House() and House(name) are called then why is not "Building" printed two times, but instead one time?

class Building {
    Building() {
        System.out.println("Buiding");
    }
    Building(String name) {
        this();
        System.out.println("Building: String Constructor"   name);
    }
}
class House extends Building {
    House() {
        System.out.println("House ");
    }
    House(String name) {
        this();
        System.out.println("House: String Constructor"   name);
    }
}
public class Test {
    public static void main(String[] args) {
        new House(" OK");
    }
}

Output:

Buiding
House
House: String Constructor OK

CodePudding user response:

House(String name) calls this() which is the same as House(). House() implicitly calls super() which is the same as Building().

You never call Building(String name).

House(String name) could call super(name) to do that.

CodePudding user response:

The basic rule of a compiled constructor below is the compiled form of a constructor

  1. Call to either a current class constructor this(args if any) or to a superclass constructor super(args if any). If it's not present then the compiler will keep this super().
  2. Call the instance block.
  3. Rest of the code written in the .java file

Java code

Bean () {
    System.out.println("Inside Bean()");
}

After Compilation

Bean () {
    super(); // added by compiler
    // call to instance block
    System.out.println("Inside Bean()");
}

So once you follow this rule then you can understand that from House(String name) the call will be going to House() because you gave this(). From House() the first call will be super() (because there is no call given manually by you), which will only invoke Building() and the same will again call super(), which in this case is Object class.

  • Related