...
Overridden/hidden method modifier | Overriding/hiding method modifier |
---|---|
public | public |
protected | protected or public |
default | default or protected or private |
privateanything but private | Cannot be overridden |
This also means that there is potential for some functionality having a restrictive modifier to be overridden by a less restrictive modifier.
...
This noncompliant code example exemplifies how a malicious subclass Sub
can override the doLogic
method of the super class. Any user of Sub
will be able to invoke the doLogic
method even though since the base class BadScope
defined it with the private
access protected
access modifier. The class Sub
can allow more access than BadScope
by using the public
modifier.
Code Block | ||
---|---|---|
| ||
class BadScope { privatepublic void doLogic() { System.out.println("Super invoked"); } } public class Sub extends BadScope { public void doLogic() { System.out.println("Sub invoked"); //do restrictive operations } } |
...
Do not override a method unless absolutely necessary. Declare all methods and fields final
to avoid malicious subclassing. This is in compliance with <xyz rule>the tenets of OBJ31-J. Misusing public static variables and OBJ00-J. Declare data members private.
Code Block | ||
---|---|---|
| ||
class BadScope { private final void doLogic() { System.out.println("Super invoked"); } } |
Risk Assessment
Subclassing allows access restrictions to be weakened, possibly compromising the security of a Java application.
...