I want to define some general post-build behavior for a group of classes. When you have common behaviors in different classes, Java tells us to extract them to the parent class.
It is clear that it makes sense, we say, for objects of this type (and its subclasses) to process post-processing after some processing;
In practice, this is difficult to do. You obviously cannot put it in the constructor of the parent class, because the parent constructor is called before the constructor of the subclass. I could write the postInit () method in the parent class and require all subclasses to call this their last statement in their constructors, but it does not look very clean because there is no way to enforce it and people forget.
Maybe some kind of language construct that I donβt know about can solve my problem?
thanks
Just a little more info about the requirement. Factory methods, etc., which are offered by many of the answers (which I approved) below, are good ideas, but I don't have that luxury. The actual situation is this, I have this parent class, which is extended by several dozen subclasses, which, in turn, are used in many other places. So redesign of how these subclasses are used is out of the question, and changing all subclasses is possible at the border. Ideally, I just need to change the parent class so that I ask.
source share