I want to call an abstract method, generateId()
, in the constructor of an abstract super class, where this abstract method depends on some fields of the respective subclasses. Consider the following pieces of code for clarity:
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() {
// Some operations that use fieldSub1
}
}
Subclass: Sub2
public class Sub2 extends SuperClass {
private SomeOtherType fieldSub2;
public Sub2(SomeOtherType fieldSub2) {
this.fieldSub2 = fieldSub2;
super();
}
protected void generateId() {
// Some operations that use fieldSub2
}
}
However, the subclass constructors won't work because the super();
must be the first statement in a constructor.
OTOH, if I make super();
the first statement in the constructors of the subclasses, then I won't be able to call generateId()
in SuperClass
. Because generateId()
uses fields in subclasses, where these fields must be initialized before being used.
The only way to "solve" this problem appears to me: Remove the call to generateId()
in the superclass. Place a call to generateId()
at the end of constructors of each subclass. But this results in code duplication.
So is there any way to solve this problem without duplicating my code? (That is, without calling generateId()
at the end of constructors of each subclass?)