We know constructor is a special method of any class that is used to initialise the objects at the time of declaration. What about constructors when the members of parent class are available to child class through inheritance? Will constructors go to child class? The answer is, of course No.
Constructors or parent class won’t participate directly in the inheritance. But it is the responsibility of the constructor of child class to make call to its parent class constructor. The default constructor of parent class is automatically being called by child class constructor. But the parameterized constructor of parent class should be called with super() method from child class constructor.
The invocation of parent class constructor must be the first statement in the child class constructor.
//Example code showing how child constructor calls parent constructor
class parent
{
parent()
{
System.out.println(“I am constructor of Parent”);
}
}
class child extends parent
{
child()
{
System.out.println(“I am constructor of Child”);
}
}
public class ConstInherEg1 {
public static void main(String[] args) {
child obj=new child();
}
}
//Example code2 showing how child constructor calls parent constructor
class parent
{
int x;
parent()
{
System.out.println(“I am default constructor of Parent”);
}
parent(int x)
{
this.x=x;
System.out.println(“I am parameterized constructor of Parent”);
}
}
class child extends parent
{
child()
{
System.out.println(“I am constructor of Child”);
}
}
public class ConstInherEg1 {
public static void main(String[] args) {
child obj=new child();
}
}
//Example code3 showing how child constructor calls parent constructor
class parent
{
int x;
parent()
{
System.out.println(“I am default constructor of Parent”);
}
parent(int x)
{
this.x=x; //this keyword refers to the current object
System.out.println(“I am parameterized constructor of Parent”);
}
}
class child extends parent
{
child()
{
super(2);
System.out.println(“I am constructor of Child”);
}
}
public class ConstInherEg1 {
public static void main(String[] args) {
child obj=new child();
}
}
Super keyword and Super() method
Super keyword of java is used to refer the parent class objects to access members of parent class. Super() method of java is used to call parent class constructor.
//Example code showing working of super keyword
class fourWheeler
{
int NoGears=4;
void show()
{
System.out.println(“Number of Gears in parent= “+NoGears);
}
}
class Car extends fourWheeler
{
int NoGears=5;
void show()
{
super.show();
System.out.println(“Number of Gears in child = “+ NoGears);
System.out.println(“Number of Gears in child = “+ super.NoGears);
}
}
public class TestSuperKW {
public static void main(String[] args) {
Car obj=new Car();
obj.show();
}
}