JAVA - Usage of "this()" method

JAVA - Usage of "this()" method

In this blog, let's understand what is the usage of this() method in JAVA. The "this()" method refers to the current class constructor and can be used to call different constructors within the same class.

Please find the example below:

class Employee{
    public Employee() {
        System.out.println("Hey, I am a default Constructor");
    }
    public Employee(int empNum, String empName) {
        this();
        System.out.println("Employee Number is :"+empNum);
        System.out.println("Employee Name is :"+empName);
    }
    public Employee(int empNum, String empName, String designation){
        this(100, "Salvatore");
        System.out.println("Employee Number is :"+empNum);
        System.out.println("Employee Name is :"+empName);
        System.out.println("Employee Designation is :"+designation);
    }    
}
      Employee emp = new Employee(101, "Mikael", "Specialist");

In the above example, the "Employee" class has 3 Constructors. One default constructor and the other two are parameterized. As per this example, we are calling three parameterized constructor. Since in that statement, there is "this()" method call. In this case-control will go to two parameterized constructor. Again there is also "this()" method call in this case-control will go to the default constructor and execute in the below order.

In conclusion, "this()" method is used to call the current class constructor. It is useful for re-using the code within the class.

Please note that "this()" method should be in the first statement in the constructor. If it's not then it will result compile time error. It's because constructor's first statement will be executed first before any other statements. Also, a constructor can call only another constructor within the same class. We cannot call a constructor from a different class by using "this()" method.

NOTE: Recursive constructor call is not allowed, it will throw compile time error.

Please make sure that you are experimenting with the "this()" method and see how it can be used in your code.

Thank You for Reading :-)