Running a method after the constructor of any derived class
- by Alexey Romanov
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.