Wiki Markup |
---|
According to the Java Language Specification \[[JLS 05|AA. Java References#JLS 05]\], section 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.
...
Noncompliant Code Example
This noncompliant code example invokes the doLogic()
method from the class constructor. The super class doLogic
superclass's doLogic()
method gets invoked on the first call, however, the overriding method is invoked on the second one. In the second call, the issue is that the constructor for SubClass
initiates the super class's constructor which undesirably ends up calling SubClass
's doLogic()
method. The value of color
is left as null
because the initialization of the class SubClass
has not yet concluded.
Code Block | ||
---|---|---|
| ||
class BaseClass { public BaseClass() { doLogic(); } public void doLogic() { System.out.println("This is super-class!"); } } class SubClass extends BaseClass { private String color = null; public SubClass() { super(); color = "Red"; } public void doLogic() { // Color becomes null System.out.println("This is sub-class! The color is :" + color); //color becomes null //other Other operations } } public class Overridable { public static void main(String[] args) { BaseClass bc = new BaseClass(); //prints Prints "This is super-class!" BaseClass sc = new SubClass(); //prints Prints "This is sub-class! The color is :null" } } |
...
This compliant solution declares the doLogic()
method as final
so that it is no longer overridable.
...
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. An equally dangerous idea is to disobey this advice by calling an overridden method from a the finalize()
method. This can prolong the subclass' life and in fact render the finalization call useless (See the example in OBJ02-J. Avoid using finalizers). Additionally, if the subclass's finalizer has terminated key resources, invoking its methods from the superclass might may lead one to observe the object in an inconsistent state and in the worst case result in the infamous NullPointerException
.
...
Allowing a constructor to call overridable methods may give an attacker access to the this
reference before an object is fully initialized which, in turn, could lead to a vulnerability.
...