Brian Tracy
Brian Tracy

Reputation: 6831

Using this() in constructor

In the online Java tutorials provided by Oracle, I saw the following.

public class Rectangle {
    private int x, y;
    private int width, height;

    public Rectangle() {
        this(0, 0, 1, 1);
    }
    public Rectangle(int width, int height) {
        this(0, 0, width, height);
    }
    public Rectangle(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
    ...
}

The first two contructors use the this() function to set the class's instance variables. Is there a reason that the third constructor does not simply utilize this(x,y,width,height).
Note: Is this simply to show (in a tutorial setting) that this is also a keyword and can also be used to set instance variables?

Upvotes: 2

Views: 8409

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279900

Is there a reason that the third constructor does not simply utilize this(x,y,width,height).

Because it is the constructor that would be invoked with

this(x, y, width, height);

and that would cause an infinite recursive loop.


As Keppil said in the comments, this is a keyword. When used like

this(x, y, width, height);

in a constructor, it invokes the class constructor with the appropriate parameter list. In this case, that constructor is the third constructor. So what you are suggesting is that the third constructor invoke the third constructor which invokes the third constructor, ad nauseam.

Upvotes: 6

Related Questions