Write a Java Program to Call One Constructor from another

In Java, a constructor is a special method used to initialize an object’s state.

A class can have multiple constructors with different parameters.

It is possible to call one constructor from another using the this() keyword.

In this tutorial, we will explore how to call one constructor from another in Java.


Let’s say we have a class Person with two constructors:

public class Person {
    private String name;
    private int age;
    
    public Person(String name) {
        this.name = name;
        this.age = 0;
    }
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

We can see that the first constructor takes only the name of the person as an argument and sets the age to 0.

The second constructor takes both the name and the age as arguments.

To call one constructor from another, we use the this() keyword.

Let’s modify the above class to call one constructor from another:

public class Person {
    private String name;
    private int age;
    
    public Person(String name) {
        this(name, 0);
    }
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

In the modified code, we have called the second constructor from the first constructor using the this() keyword.

When the first constructor is called, it invokes the second constructor with the name and age passed as arguments.

The second constructor then initializes the object’s state with the values passed.

The this() keyword can only be used in the constructor and must be the first statement in the constructor.

It is also important to note that we cannot call more than one constructor from the same constructor using the this() keyword.


In conclusion, calling one constructor from another in Java can be achieved using the this() keyword.

It can help to reduce code duplication and improve the maintainability of our code.