What is constructor chaining in Java?

Java 8Object Oriented ProgrammingProgramming

Constructors are similar to methods but,

  • They do not have any return type.
  • The name of the constructor is same as the name of the class.
  • Every class has a constructor. If we do not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class.
  • Each time a new object is created, at least one constructor will be invoked.
  • A class can have more than one constructor.

this() and super() are used to call constructors explicitly. Where, using this() you can call the current class’s constructor and using super() you can call the constructor of the super class.

You can also call one constructor from another.

Calling a constructor of one class from other is known as constructor chaining. From normal (default) constructor you can call the parameterized constructors of the same class using this() and, from the sub class you can call the constructor of the super class using super()

Example

Live Demo

class Super{
   Super(int data){
      System.out.println("value is : "+ data);
   }
}
public class Sub extends Super{
   Sub(int data) {
      super(data);
   }
   public static void main(String args[]){
      Sub sub = new Sub(400);
   }
}

Output

value is : 400
raja
Published on 02-Jan-2018 06:23:25
Advertisements