Java - Calling a Constructor from another Constructor

Introduction

A constructor may call another constructor of the same class.

The following Test class declares two constructors: one accepts no parameters and one accepts an int parameter.

public class Test {
        Test() {
        }

        Test(int x) {
        }
}

To call the constructor with an int parameter from the constructor with no parameter, use this keyword.

public class Test {
        Test() {
            // Call another constructor
            this(1); // OK. use the keyword this.
        }

        Test(int x) {
        }
}

Rule

To ensure that one constructor is executed only once during the process of an object creation of a class.

  • If a constructor calls another constructor, it must be the first executable statement in the constructor's body.
  • A constructor cannot call itself because it will result in a recursive call.

Related Topic