...
Unlike C++, the Java programming language does not specify altered rules for method dispatch during the creation of a new class instance. If methods are invoked that are overridden in subclasses in the object being initialized, then these overriding methods are used, even before the new object is completely initialized.
This means that a method may use uninitialized data that causes Consequently, invocation of an overridable method during object construction may cause use of uninitialized data, leading to runtime exceptions or leads to unanticipated outcomes. Calling overridable methods from constructors can also result in leak the escaping of the this
reference before construction has concluded. (object construction is complete, potentially exposing uninitialized or inconsistent data to other threads. See guideline TSM01-J. Do not let the (this) reference escape during object construction for additional information. )
Noncompliant Code Example
...
The doLogic()
method is invoked from the superclass's constructor. When the superclass is constructed directly, the doLogic()
method in the superclass is invoked without issueand executes successfully. However, when the subclass initiates the super class's construction, the subclasses' doLogic()
method is invoked instead. In this case, the value of color
is still null
because the subclasses constructor has not yet concluded.
...
This compliant solution declares the doLogic()
method as final
so that it is no longer overridablecannot be overridden.
Code Block | ||
---|---|---|
| ||
class SuperClass { public SuperClass() { doLogic(); } public final void doLogic() { System.out.println("This is super-class!"); } } |
...
Guideline | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MET04-J | medium | probable | medium | P8 | L2 |
Automated Detection
TODOAutomated detection of constructors that contain invocations of overridable methods appears to be straight forward.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this guideline on the CERT website.
Bibliography
Wiki Markup |
---|
\[[ESA 2005|AA. Bibliography#ESA 05]\] Rule 62: Do not call non-final methods from within a constructor. \[[JLS 2005|AA. Bibliography#JLS 05]\] [Chapter 8, Classes|http://java.sun.com/docs/books/jls/third_edition/html/classes.html], 12.5 "Creation of New Class Instances" \[[SCGRogue 20072000|AA. Bibliography#SCG 07]\] Guideline 4-3 Prevent constructors from calling methods that can be overridden \[[ESA 2005|AA. Bibliography#ESA 05Bibliography#Rogue 2000]\] Rule 6281: Do not call non-final methods from within a constructor. \[[RogueSCG 20002007|AA. Bibliography#RogueBibliography#SCG 200007]\] Rule 81: Do not call non-finalGuideline 4-3 Prevent constructors from calling methods fromthat withincan abe constructor.overridden |
...
05. Methods (MET) MET05-J. Do not use overloaded methods to differentiate between runtime types