Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Force subclasses to call super method after constructor

I want a bunch of subclasses to call a super method after finishing the constructor like this:

public abstract class Superclass {

    ...

    public Superclass(...) {
        ...    // do stuff before initializing subclass
    }

    protected void dispatch() {     //method to be called directly after creating an object
        doStuff();
        ...
    }

    public abstract void doStuff();
}

public class Subclass extends Superclass {

    ...

    public Subclass(...) {
        super(...);     //has to be the first line
        ...             //assign variables etc.
        dispatch();     //has to be called after variables are assigned etc.
    }

    public void doStuff() {
        //do stuff with assigned variables etc.
    }
}

The dispatch() function contains a set of things to do with the object after it has been created, which has to apply to all subclasses. I can't move this function into the super constructor, since it calls methods from the subclasses which require already assigned variables. But since super() requires to be the first line of the sub constructor though, I can't set any variables until after the super constructor was called.

It would work as it is now, but I find it a bad concept to call dispatch() at the end of every subclasses' constructor. Is there a more elegant way to solve this? Or should I even completely rethink my concept?

like image 410
StrikeAgainst Avatar asked Mar 05 '23 22:03

StrikeAgainst


1 Answers

Your request violates several Java best practices, e.g.:

  • Do not do complex configuration in a constructor, only fill private (final) member variables and do only very basic consistency checks (if any at all).

  • Do not call non private or non final methods from the constructor, not even indirectly.

So I would strongly suggest to think over the design of your classes. Chances are, that your classes are too big and have too many responsibilitis.

like image 90
Timothy Truckle Avatar answered Mar 23 '23 20:03

Timothy Truckle