Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Parasoft Jtest 2021.1

...

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
bgColor#FFCCCC
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.

ToolVersionCheckerDescription
CodeSonar Include PageCodeSonar_V
CodeSonar_VFB.CORRECTNESS.BOA_BADLY_OVERRIDDEN_ADAPTERClass overrides a method implemented in super class Adapter wrongly
Parasoft Jtest
Include Page
java:
Parasoft_V
java:
Parasoft_V
OOP
CERT.MET07.AHSM
Implemented
Do not hide inherited "static" member methods

Bibliography

...


...