Does a class inherit constructors from its superclass?
The answer is No.Constructors cannot be inherited.Constructors are used to initialize a valid sate of an object.Whenever a subclass instance is created then it calls no argument default constructor of super class.
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.
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.