I need this because the constructor in the superclass is calling a method which is overridden in the subclass. The method returns a value which is passed to the subclass’ constructor. But the superclass constructor must be called before the subclass constructor, so I have no chance to save the value passed in.
Share
Calling an overridden method from the superclass constructor is simply not going to work – don’t do it. The superclass constructor must always finish before that of the subclass. While the superclass constructor is executing, the object in question is a (half initialized) instance of the superclass, not the subclass! So if you try to call any overridden function from the constructor, the subclass fields it may depend on are not yet initialized (just as you have observed). This is a fundamental fact of class design, and there is no workaround.
As explained in Effective Java 2nd. Ed. (Chapter 4, Item 17):
If you can change the superclass implementation, try moving the call to the virtual function out of the constructor. One way to achieve this is using a Factory Method:
Note that the constructor of
Subclassis private to ensure that it can only be instantiated viacreateInstance(), thus instances are always initialized properly. OTOH this also prevents further subclassing. However, subclassing a concrete class is not recommended anyway – a class meant to be subclassed should be abstract (with aprotectedconstructor in this case). And of course, any further subclasses must also have non-public constructors and static factory methods which diligently callinit()…