...
Invocation of an overridable method during object construction may result in the use of uninitialized data, leading to runtime exceptions or to unanticipated outcomes. Calling overridable methods from constructors can also leak the this
reference before object construction is complete, potentially exposing uninitialized or inconsistent data to other threads (see TSM01-J. Do not let the this reference escape during object construction for additional information). As a result, constructors a class's constructor must invoke (directly or indirectly) only methods in that class that are static, final or private.
...
Code Block | ||
---|---|---|
| ||
class SuperClass { public SuperClass () { doLogic(); } public void doLogic() { System.out.println("This is superclass!"); } } class SubClass extends SuperClass { private String color = null; public SubClass() { super(); color = "Red"red"; } public void doLogic() { System.out.println("This is subclass! The color is :" + color); // ... } } public class Overridable { public static void main(String[] args) { SuperClass bc = new SuperClass(); // Prints "This is superclass!" SuperClass sc = new SubClass(); // Prints "This is subclass! The color is :null" } } |
...
Allowing a constructor to call overridable methods can provide an attacker with access to the this
reference before an object is fully initialized, which could lead to a vulnerability.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MET05-J | Medium | Probable | Medium | P8 | L2 |
Automated Detection
Automated detection of constructors that contain invocations of overridable methods is straightforward.
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
PVS-Studio |
| V6052 | |||||||
SonarQube |
| S1699 | Constructors should only call non-overridable methods | ||||||
SpotBugs |
|
...
| MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR | Implemented (since 4.5.0) |
Related Guidelines
Inheritance [RIP] | |
Guideline 7-4 / OBJECT-4: Prevent constructors from calling methods that can be overridden |
Bibliography
[ESA 2005] | Rule 62, Do not call nonfinal methods from within a constructor |
[JLS 2015] | Chapter 8, "Classes" |
Rule 81, Do not call non-final methods from within a constructor |
...
...