Java Program to Call One Constructor from another

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Java program to call one constructor from another

class Main {

  int sum;

  // first constructor
  Main() {
    // calling the second constructor
    this(5, 2);
  }

  // second constructor
  Main(int arg1, int arg2) {
    // add two value
    this.sum = arg1 + arg2;
  }

  void display() {
    System.out.println("Sum is: " + sum);
  }

  // main class
  public static void main(String[] args) {

    // call the first constructor
    Main obj = new Main();

    // call display method
    obj.display();
  }
}

Output

Sum is: 7

In the above example, we have created a class named Main. Here, you have created two constructors inside the Main class.

Main() {..}

Main(int arg1, int arg2) {...}

Inside the first constructor, we have used this keyword to call the second constructor.

this(5, 2);

Here, the second constructor is called from the first constructor by passing arguments 5 and 2.

Note: The line inside a constructor that calls another constructor should be the first line of the constructor. That is, this(5, 2) should be the first line of Main().


Example 2: Call the constructor of the superclass from the constructor of the child class

We can also call the constructor of the superclass from the constructor of child class using super().

// superclass
class Languages {

  // constructor of the superclass
  Languages(int version1, int version2) {

    if (version1 > version2) {
      System.out.println("The latest version is: " + version1);
    }

    else {
      System.out.println("The latest version is: " + version2);
    }

  }
}

// child class
class Main extends Languages {

  // constructor of the child class
  Main() {
    // calling the constructor of super class
    super(11, 8);
  }

  // main method
  public static void main(String[] args) {

    // call the first constructor
    Main obj = new Main();

  }
}

Output

The latest version is: 11

In the above example, we have created a superclass named Languages and a subclass Main. Inside the constructor of the Main class, notice the line,

super(11, 8);

Here, we are calling the constructor of the superclass (i.e. Languages(int version1, int version2)) from the constructor of the subclass (Main()).

 

Did you find this article helpful?