Wiki Markup |
---|
According to the Java Language Specification \[[JLS 05|AA. Java References#JLS 05]\], section 8.4.8.3 "Requirements in Overriding and Hiding": |
The access modifier of an overriding or hiding method must provide at least as much access as the overridden or hidden method, or a compile-time error occurs.
...
This noncompliant code example exemplifies how a malicious subclass Sub
can override the doLogic()
method of the super classsuperclass. Any user of Sub
will be able to invoke the doLogic
method as the base class BadScope
defined defines it with the protected
access modifier. The class Sub
can allow more access than BadScope
by using the public
modifierdeclaring its own version of the doLogic()
method {{public}.
Code Block | ||
---|---|---|
| ||
class BadScope { protected void doLogic() { System.out.println("Super invoked"); } } public class Sub extends BadScope { public void doLogic() { System.out.println("Sub invoked"); //do Do restrictivesensitive operations } } |
Compliant Solution
Do not override a method unless absolutely necessary. Declare all methods and fields final
to avoid malicious subclassing. Also, do not increase When this is not possible, refrain from increasing the accessibility of overridden methods. This is in compliance with the tenets of SEC05-J. Minimize accessibility of classes and their members.
Code Block | ||
---|---|---|
| ||
class BadScope { protected final void doLogic() { // declare as final System.out.println("Super invoked"); // Do sensitive operations } } |
Noncompliant Code Example
...
In addition, refrain from increasing the accessibility of an inherited method, as doing so may break assumptions made by the superclass. A class that overrides the
protected java.lang.Object.finalize
method and declares that methodpublic
, for example, enables hostile callers to finalize an instance of that class, and to call methods on that instance after it has been finalized. A superclass implementation unprepared to handle such a call sequence could throw runtime exceptions that leak private information, or that leave the object in an invalid state that compromises security.
...