Saturday, September 1, 2018

Constructor Chaining In Java with Examples

Calling a constructor from the another constructor of same class is known as Constructor chaining. The real purpose of Constructor Chaining is that you can pass parameters through a bunch of different constructors, but only have the initialization done in a single place. This allows you to maintain your initialization from a single location, while providing multiple constructors to the user. If we don’t chain, and two different constructors require a specific parameter, you will have to initialize that parameter twice, and when the initialization changes, you’ll have to change it in every constructor, instead of just the one.

Rules of constructor chaining :
1. The this() expression should always be the first line of the constructor.
2. There should be at-least be one constructor without the this() keyword (constructor 3 in below example).
3. Constructor chaining can be achieved in any order.

class Employee
    public String empName;
    public int empSalary;
    public String address;

    //default constructor of the class
    public Employee()
     //this will call the constructor with String param

    public Employee(String name)
     //call the constructor with (String, int) param
     this(name, 8765);
    public Employee(String name, int sal)
     //call the constructor with (String, int, String) param
     this(name, sal, "Delhi");
    public Employee(String name, int sal, String addr)

    void disp() {
     System.out.println("Employee Name: "+empName);
     System.out.println("Employee Salary: "+empSalary);
     System.out.println("Employee Address: "+address);
    public static void main(String[] args)
        Employee obj = new Employee();

Output :
Employee Name: Skptricks
Employee Salary: 8765
Employee Address: Delhi

This is a simple solution, to call one constructor from another in Java. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

No comments:

Post a Comment