Java: post processing after executing subclass constructor

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.

+6
source share
3 answers

If you cannot use the factory method for pragmatic reasons, the best solution I can think of is to create a protected final method in the root class that performs post-processing and add a method call to each leaf class; eg.

 public abstract class Root { ... protected final void finishInit() { // Do post-processing } } public abstract class Intermediate { ... protected Intermediate(...) { super(...); ... // don't call finishInit(); } ... } public class Leaf { ... public Leaf(...) { super(...); ... finishInit(); } ... } 

If Intermediate not abstract , then you will need a separate public constructor for instantiation, which calls finishInit() at the end.


All this is a little awkward, but it's a fine you have to pay if you cannot / will not reorganize your code to use factory methods.

+3
source

One solution is to not have a public ctor. You may have a factory method that completes initialization before returning the object to the caller.

+2
source

Well, the simplest solution is to add a template for this class hierarchy in the IDE.

Have you thought about your design and how you can change it? Maybe you need some kind of design template, for example Factory Method, Abstract Factory, Builder?

+2
source

Source: https://habr.com/ru/post/887331/


All Articles