Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract methods in an abstract class constructor: design flaw?

Tags:

java

oop

I have an abstract class Entity. Every class extending Entity will need some default and some customizable setup:

public abstract class Entity {

    protected Entity() {
        // ... default setup
        customSetup();
    }

    protected abstract void customSetup();
    // ...
}

My extending class MyEntity takes a parameter in the constructor, that will be used in customSetup():

public class MyEntity extends Entity {

    private Data data;

    public MyEntity(Data d) {
        super(); // in here customSetup() is called!
        data = d;
    }

    @Override
    protected void customSetup() {
        codeDependingOn(data); // will throw NPE: data==null yet!
    }
}

As comments state, this code won't work.

I could just throw away customSetup() and put all the custom code after super(), but having that abstract method makes clearer what you're supposed to put there.

I feel like I'm violating some rule of OOP design. What's the correct way to do what I want?

like image 207
bigstones Avatar asked Oct 20 '11 17:10

bigstones


1 Answers

This is generally a bad idea to call methods which can be overriden from a constructor. The problem is that the class is not yet fully initialized, and when the method is called in a subclass, it may cause trouble.

Take a look at this question: What's wrong with overridable method calls in constructors?, it has a good explanation.

like image 128
Malcolm Avatar answered Sep 17 '22 16:09

Malcolm