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.
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, a class's constructor must invoke (directly or indirectly) only methods in that class that are static, final or private.
Noncompliant Code Example
This noncompliant code example results in the use of uninitialized data by the
doLogic() method is invoked from the superclass's constructor. When the superclass is constructed directly, the
doLogic() method in the superclass is invoked and executes successfully. However, when the subclass initiates the superclass's construction, the subclass's
doLogic() method is invoked instead. In this case, the value of
color is still
null because the subclass's constructor has not yet concluded.
This compliant solution declares the
doLogic() method as final so that it cannot be overridden:
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.
Automated detection of constructors that contain invocations of overridable methods is straightforward.
|S1699||Constructors should only call non-overridable methods|
|MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR||Implemented (since 4.5.0)|
Guideline 7-4 / OBJECT-4: Prevent constructors from calling methods that can be overridden
Rule 62, Do not call nonfinal methods from within a constructor
Rule 81, Do not call non-final methods from within a constructor