Search code examples
javac++constructoroverridingfactory-pattern

Alternatives to using overridden methods in constructors, Java


In a Java project I am coding I have ended up using methods that are overridden in constructors. Something like:

class SuperClass {
    SuperClass() {
        intialise();
    }

    protected void initialise() {
        //Do some stuff common to all subclasses
        methodA();
        methodB();
    }

    protected abstract void methodA();

    protected abstract void methodB();
}

class SubClass1() {
    SubClass() {
        super();
    }
    protected void methodA() { //Do something }
    protected void methodB() { //Do something }

}

class SubClass2() {
    SubClass() {
        super();
    }
    protected void methodA() { //Do something else }
    protected void methodB() { //Do something else}

}

I now realise, that although in my case it works fine, it is somewhat dangerous since SubClass methods are called on an object that has currently only been constructed as a SuperClass object (something that may be overlooked when new classes that extend SuperClass are added in the future). It also wouldn't work in c++ due to differences in how objects are created.

The only way I can think to get round this is to move the initialise method call down to the concrete classes constructor:

   class SuperClass {
    SuperClass() {            
    }

    protected void initialise() {
        methodA();
        methodB();
    }

    protected abstract void methodA();

    protected abstract void methodB();
}

class SubClass1() {
    SubClass() {
        super();
        initialise();
    }
    protected void methodA() { //Do something }
    protected void methodB() { //Do something }

}...

Is this the common way to over come this issue? It seems a shame (and easy to forget) that all further classes that extend SuperClass need to remember to call initialise().

I also found myself doing something similar in a more complicated situational that uses a Factory Method in a constructor, which is overridden in subclasses to decide which concrete class to implement. The only other way I can think to get round this and keep the design pattern as is, is to perhaps construct in a two phase process; i.e. construct with the bare minimum, and then call a second method to finish off the job.


Solution

  • This is really not a good idea as your Subclass will not be properly constructed when its methodA() and methodB() are called. That would be very confusing for people extending the class. Recommend you use an abstract init() instead, as suggested by dlev in his/her comment.