Let\'s say I have a Java class
abstract class Base {
abstract void init();
...
}
and I know every derived class will have to call <
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();
}
Or use spring... you can do <beans default-init-method="init">
, see Default initialization and destroy methods.
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.
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.
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.
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.