Running a method after the constructor of any derived class

Posted by Alexey Romanov on Stack Overflow See other posts from Stack Overflow or by Alexey Romanov
Published on 2010-05-25T17:32:08Z Indexed on 2010/05/25 18:01 UTC
Read the original article Hit count: 108

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about java

Related posts about oop