how to call one constructor from another constructor in java

How to call one constructor from another constructor in java?

In Java, you can call one constructor from another constructor in the same class using the this() keyword. This is known as constructor chaining. Constructor chaining allows you to reuse code and avoid redundancy when multiple constructors are defined in a class.

Here’s the basic syntax for calling one constructor from another constructor using the this() keyword:

 * Author: Zameer Ali
 * */
public class MyClass {
    // First constructor
    public MyClass() {
        // Code for the first constructor

    // Second constructor that calls the first constructor using this()
    public MyClass(int value) {
        this(); // Calls the default constructor
        // Code specific to the second constructor

    public static void main(String[] args) {
        // Create objects of the class
        MyClass obj1 = new MyClass(); // Calls the first constructor
        MyClass obj2 = new MyClass(10); // Calls the second constructor

In the example above, the second constructor MyClass(int value) calls the default constructor MyClass() using this(). By doing this, the code inside the default constructor is executed first, followed by the code inside the second constructor. This way, you can reuse initialization logic defined in one constructor in another constructor of the same class.

Leave a Reply

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