I am confused why the following pattern's call to the other constructor block does not count as the first statement in the constructor block:
public class MyClass
{
final String someProperty;
public MyClass()
{
/* some default logic */
}
public MyClass(String someProperty)
{
this().someProperty = someProperty;
}
}
It seems to me like the order of operations should be:
- The empty constructor runs.
- The property gets assigned.
However, I get a compile error:
Call to another constructor must be the first statement in constructor block
Edits
I realize that I can just separate the calls.
public MyClass(String someProperty)
{
this();
this.someProperty = someProperty;
}
However, it sure would be nice to be able to one-line this constructor chaining. I am trying to understand why this()
behaves differently than new MyClass()
. They both run the empty constructor! But they allow for different behavior after the constructor completes. Note that I can chain directly off the constructor when using the fluent pattern.
new MyClass().doSomeStuff().doOtherStuff();