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

NOTE: This article is 3 years or older so its information may no longer be relevant. Read on at your own discretion! Comments for this article have automatically been locked, refer to the FAQ for more details.
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.


Skip down to comments...
A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. If you spot something out of place, please do let me know.

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.
comments powered by Disqus
Other posts you may like...