Search code examples
javafinal

"Once-initialized" variables that are not initialized in construction time


Is there any way in Java to create variables like final that are not initialized inside the constructor, but yet once they are initialized they can never be changed again? My problem is that I get the variable values at different time points and I'd like to create the class before or as soon as I receive the first value.

I've already thought about the obvious solution of keeping a flag for each variable, but I wanted to know if there's anything more efficient than that.


Solution

  • I would probably do something along the lines of the last answer here. Always set the fields with a setter, and if the field is not the default value (i.e. null), do not allow it to be set.