...
In this noncompliant code example, the programmer hides the static method rather than overriding it. Consequently, the code invokes the displayAccountStatus()
method of the superclass at two different call sites instead of invoking the superclass method at one call site and the subclass method at the other, causing it to print Account details for admin
despite being instructed to choose user
rather than admin
.
Code Block | ||
---|---|---|
| ||
class GrantAccess { public static void displayAccountStatus() { System.out.println("Account details for admin: XX"); } } class GrantUserAccess extends GrantAccess { public static void displayAccountStatus() { System.out.println("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"); } } |
...
Confusing overriding and hiding can produce unexpected results.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MET07-J | Low | Unlikely | Medium | P2 | L3 |
Automated Detection
Automated detection of violations of this rule is straightforward. Automated determination of cases in which method hiding is unavoidable is infeasible. However, determining whether all invocations of hiding or hidden methods explicitly indicate which specific method is invoked is straightforward.
Tool | Version | Checker | Description |
---|
Parasoft Jtest |
| CERT.MET07.AHSM | Do not hide inherited "static" member methods |
Bibliography
Puzzle 48, "All I Get Is Static" | |
[JLS 2015] |
...
...