1

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?

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • 1
    It will call the constructor with two parameters. – Luiggi Mendoza Nov 28 '14 at 21:20
  • 1
    Yes it's calling the constructor with two parameters which as a `Status` as first parameter and the return type of `PluginResult.StatusMessages[status.ordinal()]` as second parameter. – Alexis C. Nov 28 '14 at 21:20

2 Answers2

1

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.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • This approach is needed, as I understand, because I can't specify default value of `PluginResult.StatusMessages[status.ordinal()]` for one of constructors, correct? – Max Koretskyi Nov 28 '14 at 21:29
  • That's correct: you can't provide default arguments in Java. – nneonneo Nov 28 '14 at 21:45
  • Yep, it's clear now. Thanks. I've accepted _striving_coder_'s answer since he has less reputation, hope you don't mind :) – Max Koretskyi Nov 28 '14 at 21:47
1

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

striving_coder
  • 798
  • 1
  • 5
  • 7
  • Didn't quite understand your analogy to C++ default values of arguments, could you elaborate? – Max Koretskyi Nov 28 '14 at 21:27
  • 1
    @Maximus: Sure. In C++ you could've said something like: `public: PluginResult(Status status, string message = PluginResult.StatusMessages[status.ordinal()])` where `=` means "use the following for this parameter if none provided explicitly". Thus you effectively take care of both situations (when constructor is called with 1 argument and when constructor is called with 2 arguments) in 1 constructor definition. Hope that makes sense. – striving_coder Nov 28 '14 at 21:37
  • 1
    @Maximus: Not directly, but there are other ways to achieve relatively the same - please see here: http://stackoverflow.com/questions/997482/does-java-support-default-parameter-values – striving_coder Nov 28 '14 at 21:53