The this()
statement is used to invoke one constructor from another within the same class. It is primarily used for constructor chaining, allowing code reuse and reducing redundancy in constructor definitions.
Generally, one constructor is called if we create the object. If we want to call multiple constructors, then we use the this()
statement for achieving constructor chaining.
Constructor Chaining- calling the constructor from one constructor to another constructor of the same class, this is called the constructor chaining.
Rules
this()
calling statement is always written inside the constructor.Each constructor has only one
this()
statement.this()
statement is always written in the first line of the constructor.
Example:
package oops;
public class MasterBackend {
public MasterBackend() {
System.out.println("Master Backend");
}
public MasterBackend(int a) {
this();
System.out.println("Master Backend "+a);
}
public MasterBackend(int a, int b) {
this(a);
System.out.println("Master Backend "+a+b);
}
public MasterBackend(int a, int b, int c) {
this(a,b);
System.out.println("Master Backend "+a+b+c);
}
public static void main(String[] args) {
MasterBackend masterBackend2 = new MasterBackend(10,20,30);
}
}
Output:
Master Backend
Master Backend 10
Master Backend 1020
Master Backend 102030
super()
statement is also similar to the this()
statement of all the rules to write the super()
statement are the same as the this()
statement. However, the super()
statement is used to call the super class constructor. We will discuss super()
calling the statement after the inheritance.
Example - Recursive Constructor - compile time error
package oops;
public class MasterBackend {
public MasterBackend() {
this(12)
System.out.println("Master Backend");
}
public MasterBackend(int a) {
this();
System.out.println("Master Backend "+a);
}
public static void main(String[] args) {
MasterBackend masterBackend2 = new MasterBackend(10);
}
}
In this example, we call the zero-args constructor with a parameterized constructor and parameterized constructor zero-args constructor so this will give a compile time error.
Output:
C:\Users\Dell\OneDrive\Desktop\java-dsa-practices\src\oops\MasterBackend.java:9:9
java: recursive constructor invocation
The this()
keyword invokes another constructor within the same class, enabling constructor chaining and reducing redundancy.