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".
constructorref.jpg


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.

-i

Use of any information contained in this blog post/article is subject to this disclaimer.
comments powered by Disqus
Other posts you may like...