My problem is almost exactly the same as the problem posted here: Abstract class with final uninitialized field and I like the solution. However, my problem is a bit more complicated in that the abstract class has multiple final fields of varying types. For example, I have four int, two int[], and two double. What would be the best way to force the subclasses to initialize these variables?
Options I’ve considered:
- Convert all fields to Strings and pass with a
Map - Have a really long superclass constructor
- Create a helper class that would act as a wrapper and encapsulate all the values, then pass an instance of this class to the base class
The first option is not very elegant, and seems a bit complicated, especially with arrays. The second option is very tedious, and the third option just seems like I’m overdoing it.
Is there a “correct” way of doing this? Or if not, which of the three options posed would be the most elegant?
I would go with the second, “Have a really long superclass constructor.” If we follow the approach detailed in the question you referenced, the superclass constructor is
protectedand not meant to be called by anything external to the class hierarchy or package. My feeling always is, once something is not exposed beyond that boundary – i.e., is not part of the “API” as it were – then it doesn’t matter what it looks like. Let it have eight different parameters of varying types, or even more. Yes, it’s visible from within the package, but it’s clear from the original solution that that constructor is not meant to be called by anything other than the subclasses. That’s another motivation for non-publicvisibility.Of course, your instincts for doing something cleaner are correct when it comes to
publicstuff. The fact that you asked this question at all shows you have the right instincts.