Java: post-processing after subclass constructor completes

I want to define some common post-construction behavior for a group of classes. When you have shared behaviors in different classes, Java tells us to extract them out into a parent class.

Conceptually, it makes sense, we're saying, for objects of this type (and its subclasses), do some post-processing after it's constructed;

Practically, it's hard to do. You obviously can't put it in the parent class constructor because parent constructor is called before the subclass constructor. I could write a postInit() method in the parent class and require all subclasses to call it as their last statement in their constructors, but it doesn't seem very clean, as there's no way to enforce it, and people do forget.

Is there maybe some language construct that I'm not aware of that may solve my problem?

Thanks

Just a little more background on the requirement. Factory methods etc. that are suggested by many of the answers (which I've upvoted) below are all good ideas, but I don't really have that luxury. The actual situation is this, I have this parent class, which is extended by a couple of dozen subclasses, which are in turn used in many other places. So redesign how these subclasses are used is out of the question, and changing all subclasses is borderline possible. Ideally, I just need to change the parent class, so that's what I'm asking.

7
задан RAY 5 May 2011 в 05:12
поделиться