Is it OK to call abstract method from constructor in Java? [duplicate]
Solution 1:
This code demonstrates why you should never call an abstract method, or any other overridable method, from a constructor:
abstract class Super {
Super() {
doSubStuff();
}
abstract void doSubStuff();
}
class Sub extends Super {
String s = "Hello world";
void doSubStuff() {
System.out.println(s);
}
}
public static void main(String[] args) {
new Sub();
}
When run, this prints null
. This means the only "safe" methods to have in a constructor are private and/or final ones.
On the other hand, your code doesn't actually call an abstract method from a constructor. Instead, you pass an uninitialized object to another thread for processing, which is worse, since the thread you're starting may be given priority and execute before your Base
finishes its initialization.
Solution 2:
Not a good idea since when run() is invoked, the Derivative object may not have been initialized. If run() depends on any state in Derivative, it can fail.
In your simple case it works. But then there's no point for the subclass. You can simply
public Base(final int param, Runnable action) {
new Thread(action).start();