The following code will explain implicit call to default constructor of base class:-
class Base {
Base() {
System.out.println("I am constructing Base");
}
}
class Child extends Base {
Child() {
System.out.println("I am constructing Child");
}
}
public class A {
public static void main(String[] args) {
Child child = new Child();
}
}
Once executed this code will print:
I am constructing Base
I am constructing Child
It means when a child class object is created it inherently calls no arg default constructor of base class.


2 comments:
a clarification - so when do we use super(); in our constructor?
This is why in a sub class's constructor, the call of super constructor must be first line. The compiler inserts the implicit super class constructor (no argument constructor) if no super constructor call is found at the beginning. If super class does not have a implicit constructor and child class constructor does not call super class constructor, compiler gives an error.
Post a Comment