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
- Call to either a current class constructor
this(args if any)
or to a superclass constructorsuper(args if any)
. If it's not present then the compiler will keep thissuper()
. - Call the instance block.
- 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.