How do you handle constructor chaining in Java

date:2024-06-05 12:28:13 author:admin browse: time View comments Add Collection

How do you handle constructor chaining in Java

How do you handle constructor chaining in Java?

Constructor chaining in Java is the process of calling one constructor from another with respect to the current object. It’s done using “this()” and “super()”.

“this()” refers to a constructor within the same class, while “super()” calls a parent class constructor. Both must be the first statement in a constructor.

For example:

public class MyClass {
    int var;
    // Default constructor
    public MyClass() {
        this(10);
    }
    // Parameterized constructor
    public MyClass(int var) {
        this.var = var;
    }
}

In this code, the default constructor invokes the parameterized constructor via “this(10)”. This is an instance of constructor chaining within the same class.