Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Salesforce
  3. Question
Salesforce

How can I Call to another constructor that must be the first statement in the constructor block?

Asked by Anna Ball Apr 10, 2021 24 views 1 answer
Share

About this question

 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.

Your answer

1 Answer

More Salesforce discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Salesforce Blogs

Guides, tips and career advice on Salesforce from JanBask experts.