Is it OK to call abstract method from constructor in Java? [duplicate]

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.

Leave a Comment