Running a method after the constructor of any derived class

15,789

Solution 1

What happens in init()? It's likely that a better design could eliminate the method altogether, or at least relax the requirement that it execute after the sub-class' constructor. Be certain that init() does not make the object under construction visible to any other threads before the constructor completes, because that creates concurrency bugs.

As an (ugly) alternative, an abstract method could be implemented by sub-classes as a pseudo-constructor:

abstract class Base {
  Base() {
    ctor();
    init();
  }
  abstract void ctor();
  abstract void init();
}

Solution 2

Avoid this. If you do it, any class that extends your DerivedX class may decide to also call init() thus leaving the object in inconsistent state.

One approach is to let the init() method be invoked manually by clients of your class. Have an initialized field, and throw IllegalStateExcepion if any method that requires initialization is called without it.

A better approach would be to use a static factory method instead of constructors:

public Derived2 extends Base {
    public static Derived2 create() {
       Derived2 instance = new Dervied2();
       instance.init();
       return instance;
    }
}

Update: As you suggest in your update, you can pass Builder to a static factory method, which will call the init() on the instance. If your subclasses are few, I think this is an overcomplication, though.

Solution 3

In addition to Bozho's recommendation, an application container is excellent for the task.

Mark your init() method with the javax.annotation.PostConstruct annotation and a rightly configured EJB or Spring container will execute the method after the dependency injections are finished, but before the object can be used by the application.

An example method:

@PostConstruct
public void init() { 
    // logic..
}

In an enterprise application you can open resources to for example the files system in the init() method. This initialization can throw exceptions and should not be called from a constructor.

Solution 4

if Java had it, we wouldn't see all these init() method calls in the wild.

"surround child constructor with something" - that cannot be done in pure java. Too bad, because there can be very interesting applications, especially with anonymous class + instance initialization block.

factory and container - they can be helpful when native new doesn't do the job; but that's trivial and boring, and won't work with anonymous classes.

Solution 5

If you are adverse to using factories for some reason, you could use the following trick:

trait RunInit {
    def init():Unit
    init()
}

class Derived1 extends Base with RunInit {
    def init() = println("INIT'ing!")
}

This will run init() before the Derived1 constructor/body.

Share:
15,789
Alexey Romanov
Author by

Alexey Romanov

A programmer and mathematician. Favorite languages: Haskell, Ruby, C#.

Updated on June 19, 2022

Comments

  • Alexey Romanov
    Alexey Romanov about 2 years

    Let's say I have a Java class

    abstract class Base {
        abstract void init();
        ...
    }
    

    and I know every derived class will have to call init() after it's constructed. I could, of course, simply call it in the derived classes' constructors:

    class Derived1 extends Base {
        Derived1() {
            ...
            init();
        }
    }
    
    class Derived2 extends Base {
        Derived2() {
            ...
            init();
        }
    }
    

    but this breaks "don't repeat yourself" principle rather badly (and there are going to be many subclasses of Base). Of course, the init() call can't go into the Base() constructor, since it would be executed too early.

    Any ideas how to bypass this problem? I would be quite happy to see a Scala solution, too.

    UPDATE: Here is a generic version of the Factory Method approach:

    interface Maker<T extends Base> {
        T make();
    }
    
    class Base {
        ...
        static <T extends Base> T makeAndInit(Maker<T> maker) {
            T result = maker.make();
            result.init();
            return result;
        }
    }
    

    UPDATE 2: This question is basically "how do you use Template Method for constructors"? And the answer seems to be, "You can, but it's a bad idea". So I can do a Template Factory (Template Method + Abstract Factory) instead.