What is constructor chaining how you achieved in Java

What is constructor chaining how you achieved in Java

Answer : Constructor is chaining is the process of calling another constructor in same class or parent class. To call constructor in the same class use this() and to call parent class constructor use super(). Please have example below:

package com.javahonk.constructorchain;

public class Toyota extends Car {

	Toyota() {
		this("Java Honk");

	}

	Toyota(String name) {
		super();
		System.out.println(name);
	}

	public static void main(String args[]) {
		new Toyota();

	}

}

class Car {

	Car() {
		System.out.println("Car parent class");
	}
}

 

Output:


What is constructor chaining how you achieved in Java

Important : What really happens when calling the constructor. Please see below:

  • Toyota constructor is invoked. When you create object in child class then every constructor invokes the constructor of its superclass with an (implicit) call to super()
  • Car constructor is invoked because Car is super class of toyota (As you saw in above example output as well)
  • Finally if no more parent then Object constructor is invoked becuase Object is the superclass of all classes, so class Car extends Object class if you extends it or not. At this point we reached top of class hirarchy.
  • Object instance variables are given their explicit values and its constructor completed.
  • Car instance variables are given their explicit values (if any) and its constructor completed.
  • Toyota instance variables are given their explicit values (if any) and its constructor completed.

Important :  Why we need constructor chaining – Without constructor chaining parent wouldn’t know about children and parent must be crated before child.

Leave a Reply

Your email address will not be published. Required fields are marked *