...
The difference between these two is that the overridden method gets invoked from the subclass while the hidden method may get invoked from either the superclass or the subclass, depending on how it is invoked (name qualification).
Noncompliant Code Example
To differentiate between overriding and hiding, a common nomenclature is used. The method to be invoked is decided at either compile time (if the base method is static
, as in this noncompliant code example) according to the type of the qualifier or at run time otherwise (for non-static methods). A qualifier is a part of the invocation expression before the dot (for example, the variables admin
and user
in this noncompliant code example).
...
Code Block | ||
---|---|---|
| ||
class GrantAccess { public static void displayAccountStatus() { System.out.print("Account details for admin: XX"); } } class GrantUserAccess extends GrantAccess { public static void displayAccountStatus() { System.out.print("Account details for user: XX"); } } public class StatMethod { public static void choose(String username) { GrantAccess admin = new GrantAccess(); GrantAccess user = new GrantUserAccess(); if(username.equals("admin")) { admin.displayAccountStatus(); } else { user.displayAccountStatus(); } } public static void main(String[] args) { choose("user"); } } |
Compliant Solution
This compliant solution correctly classifies this case as hiding and uses absolute, fully qualified class names GrantAccess
and GrantUserAccess
to clearly state the intent. Refrain from qualifying a static
method invocation with an expression meant for dynamic dispatch.
...
It is recommended that the @Override
annotation be used to clearly specify that a method is the overridden version and not the hidden one.
Risk Assessment
Confusing overriding and hiding can produce unexpected results.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MET00- J | low | unlikely | medium | P2 | L3 |
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[Tutorials 08|AA. Java References#Tutorials 08]\] [Overriding and Hiding Methods|http://java.sun.com/docs/books/tutorial/java/IandI/override.html] \[[Bloch 05|AA. Java References#Bloch 05]\] Puzzle 48: All I Get Is Static \[[JLS 05|AA. Java References#JLS 05]\] 8.4.6.3 Requirements in Overriding and Hiding |
...