Search code examples
javaconstructorinitializationbase-class

Is it ok to initialize final member in abstract base class using abtract method?


I wonder whether I could initialze a final field in an abstract base class with the result of an abtract method, which would be implemented by the derived class. I understand that derived ctor would call base ctor first, so I guarantee that the abtract method implementation would also depend only on defined-on-declaration final fields of the derived class. I try the following code and it seems working.

abstract class Base {
    protected final String name = calName();
    protected abstract String calName();
}

public final class Foo extends Base {
    private final String id = "42";
    @Override
    protected String calName() {
        return String.format("WithId%s", id);
    }
    public void display() {
        System.out.printf("name: %s\n", name);
        System.out.printf("id:   %s\n", id);
    }
    public static void main(String[] args) {
        var foo = new Foo();
        foo.display();
    }
}

So is this a legit action in java, or is it a very bad idea?


Solution

  • No, it is not ok.

    Call to abstract method (as well as any kind of overridable method) during object construction is a bad idea.

    Such calls may result in subtle bugs, as object initialization may happen before the method call.