Do Not Call Abstract Methods in Constructors
ID |
java.no_abstract_call_in_constructor |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
CWE:668, reliability |
Rationale
When a constructor invokes an abstract (or overridable) method, the subclass’s override executes before the subclass constructor has finished initializing its fields. This means the overridden method may see null or default values for fields that the subclass constructor has not yet assigned, leading to subtle and hard-to-diagnose bugs.
// Bad — setup() runs before SubClass fields are initialized
abstract class Base {
Base() {
setup();
}
abstract void setup();
}
class SubClass extends Base {
private String name = "default";
void setup() {
// name is still null here!
System.out.println(name.length());
}
}
Remediation
Avoid calling overridable methods from constructors. Use an explicit initialization method that callers invoke after construction, or use the Template Method pattern with final helper methods:
// Good — defer initialization
abstract class Base {
Base() {
// no abstract calls
}
abstract void setup();
}
// Caller creates and then initializes
Base b = new SubClass();
b.setup();