Java Constructors in Inheritance
It is very important to understand how the constructors get executed in the inheritance concept. In the inheritance, the constructors never get inherited to any child class.
In java, the default constructor of a parent class called automatically by the constructor of its child class. That means when we create an object of the child class, the parent class constructor executed, followed by the child class constructor executed.
Let's look at the following example java code.
class ParentClass{
int a;
ParentClass(){
System.out.println("Inside ParentClass constructor!");
}
}
class ChildClass extends ParentClass{
ChildClass(){
System.out.println("Inside ChildClass constructor!!");
}
}
class ChildChildClass extends ChildClass{
ChildChildClass(){
System.out.println("Inside ChildChildClass constructor!!");
}
}
public class ConstructorInInheritance {
public static void main(String[] args) {
ChildChildClass obj = new ChildChildClass();
}
}
When we run this code, it produce the following output.
However, if the parent class contains both default and parameterized constructor, then only the default constructor called automatically by the child class constructor.
Let's look at the following example java code.
class ParentClass{
int a;
ParentClass(int a){
System.out.println("Inside ParentClass parameterized constructor!");
this.a = a;
}
ParentClass(){
System.out.println("Inside ParentClass default constructor!");
}
}
class ChildClass extends ParentClass{
ChildClass(){
System.out.println("Inside ChildClass constructor!!");
}
}
public class ConstructorInInheritance {
public static void main(String[] args) {
ChildClass obj = new ChildClass();
}
}
When we run this code, it produce the following output.
The parameterized constructor of parent class must be called explicitly using the super keyword.