Max Koretskyi
Max Koretskyi

Reputation: 105517

calling `this` from overloaded constructor

I've stumbled upon the following code:

public class PluginResult {

    public PluginResult(Status status) {
        this(status, PluginResult.StatusMessages[status.ordinal()]); //this line
    }

    public PluginResult(Status status, String message) {
        this.status = status.ordinal();
        this.messageType = message == null ? MESSAGE_TYPE_NULL : MESSAGE_TYPE_STRING;
        this.strMessage = message;
    }

I'm wondering what it does on this line:

this(status, PluginResult.StatusMessages[status.ordinal()]);

Is it calling another overloaded constructor of the same class?

Upvotes: 1

Views: 55

Answers (2)

striving_coder
striving_coder

Reputation: 798

Yes, exactly. It's essentially the same (from the result standpoint) as providing default values of arguments in C++.

Upvotes: 1

nneonneo
nneonneo

Reputation: 179552

Yes, this simply calls another constructor. This is quite common in Java, and you may call it "constructor delegation".

There are actually two kinds of delegation, this (which calls a constructor of the current class) and super (which calls a constructor of the superclass). They are mutually exclusive, and must appear as the first statement of a constructor.

Upvotes: 1

Related Questions