Wiki Markup |
---|
According to the Java Language Specification \[[JLS 2005|AA. Bibliography#JLS 05]\], sectionSection 12.5, "Creation of New Class Instances": |
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 and cause runtime exceptions or lead to unanticipated outcomes. Calling overridable methods from constructors can also result in the escaping of the this
reference before construction has concluded. (see See guideline TSM01-J. Do not let the (this) reference escape during object construction.) .
Noncompliant Code Example
...
In addition to constructors, do not call overridable methods from the clone()
, readObject()
and readObjectNoData()
methods as it would allow attackers to obtain partially initialized instances of classes. (see See guidelines MET07-J. Do not invoke overridable methods on the clone under construction and SER11-J. Do not invoke overridable methods from the readObject method.) . It is also insecure to call an overridden method from the finalize()
method. This can prolong the subclass' life and in fact, render the finalization call useless (See the example in guideline OBJ08-J. Avoid using finalizers.) . Additionally, if the subclass's finalizer has terminated key resources, invoking its methods from the superclass may lead one to observe the object in an inconsistent state and in the worst case result in a NullPointerException
.
...