Call One Constructor from another in Java

Exercise:

Write a Java Program to call one constructor from another.

Click Here to View the Solution!
public class CallConstructor {
  int sum;

  // first constructor
  CallConstructor() {
       this(19, 11); //calling second constructor
  }
 
  // second constructor
  CallConstructor (int arg1, int arg2) {
    this.sum = arg1 + arg2; // adding two integers
  }
  void display() {
    System.out.println("Sum = " + sum);
  }
  
  // Driver main class
  public static void main(String[] args) {
 
    // call the first constructor as it has no parameters
    CallConstructor obj = new CallConstructor ();
    obj.display();
  }
} 
Click Here to View the Output!
Sum = 30
Click Here to View the Explanation!
  • This program is used to call a constructor from another constructor within the same class.
  • A class CallConstructor is created which holds the two constructors CallConstructor() and CallConstructor(int arg1, int arg2).
  • The first constructor calls the second constructor by using the keyword this as follows: this.(19, 11).
  • The second constructor uses the values provided by the first constructor to perform the operation sum = arg1 + arg2 and display the sum.
  • It is to be noted, the first line of the constructor calling the second constructor should be the one that calls the constructor i.e. the first line of the CallConstructor() constructor should be this.(19, 11).

%d bloggers like this: