Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

Sometimes when implementing a constructor on an object that requires calling another constructor there's a need to call a helper method that does some work. This is done either for convenience or because some work needs to be done on input parameters before calling the super/this constructor. In these situations you're likely to come across an error like this - "Cannot reference 'X' before supertype constructor is called".

What does that mean exactly? Well since we are inside a constructor and the object is not yet created, it is impossible to call instance methods. The object doesn't exist so the method doesn't exist yet!

So how do we get past this? Since an instance method is not allowed we need to look at a different way of implementing our helper method. The solution - make the helper method static. Since static methods do not depend on an object being instantiated, we can call them inside the constructor even before the object is created.

This will work if the helper method doesn't rely on any member variables or other instance methods.

I've recently used this approach in jPhotoFrame. I had a situation where my object had multiple constructors and in one of the constructors I had to extract a value from a JSON object and then pass it to different constructor. The second constructor invoked the parent constructor which set all the member variables from its inputs.

I could have of course just duplicated my code for setting the member variables but decided it was cleaner to do it this way.


A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.