I want to call the abstract generateId() method in the constructor of the abstract superclass, where this abstract method depends on some fields of the corresponding subclasses. For clarity, consider the following code fragments:
Abstract class: SuperClass
public abstract class SuperClass { protected String id; public SuperClass() { generateId(); } protected abstract void generateId(); }
Subclass: Sub1
public class Sub1 extends SuperClass { private SomeType fieldSub1; public Sub1(SomeType fieldSub1) { this.fieldSub1 = fieldSub1; super(); } protected void generateId() {
Subclass: Sub2
public class Sub2 extends SuperClass { private SomeOtherType fieldSub2; public Sub2(SomeOtherType fieldSub2) { this.fieldSub2 = fieldSub2; super(); } protected void generateId() {
However, subclass constructors will not work because super(); must be the first statement in the constructor.
OTOH if I do super(); the first statement in subclass constructors, then I will not call generateId() in SuperClass . Because generateId() uses fields in subclasses where these fields must be initialized before use.
The only way I can "solve" this problem seems to me: delete the generateId() call in the superclass. Place a call to generateId() at the end of the constructors of each subclass. But this leads to code duplication.
So, is there a way to solve this problem without duplicating my code? (That is, without calling generateId() at the end of the constructors of each subclass?)
source share