Java: this(…) constructor call (with examples)

When you have multiple constructors, one constructor can call this(…) to invoke another constructor.

Example: The no-arg constructor delegates to the constructor that takes two arguments.

class Complex() {
    double im;
    double re;

    public Complex() {
        this(0, 0);  // Call other constructor
    }

    public Complex(double initialIm, double initialRe) {
        im = initialIm;
        re = initialRe;
    }
}

There are a few constraints to keep in mind:

The this(…) call is similar to calling super(…). See article Calling super().

Comments

Be the first to comment!