Abstract methods in an abstract class constructor: design error?

I have an abstract class Entity . For each class that extends Entity , you will need some default setting and some custom setting:

 public abstract class Entity { protected Entity() { // ... default setup customSetup(); } protected abstract void customSetup(); // ... } 

My extensible class MyEntity takes a parameter in the constructor, which 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 stated in the comments, this code will not work.

I could just throw away customSetup() and put all the user code after super() , but using this abstract method it’s clearer to choose what you have to put there.

I feel like I’m breaking some rule of OOP design. What is the right way to do what I want?

+8
java design oop
source share
1 answer

As a rule, it is a bad idea to call methods that can be overridden by the constructor. The problem is that the class is not yet fully initialized, and when the method is called in a subclass, it can cause problems.

Take a look at this question: What is wrong with overridable method calls in constructors? He has a good explanation.

+9
source share

All Articles