...
Programmers may confuse hiding with overriding. An instance method defined in a subclass overrides another instance method in the superclass when
...
both have the same name
...
, number and type of parameters
...
, and the return type.
Hiding and overriding differ in the determination of which method is invoked from a call site. For overriding, the method invoked is determined at runtime based on the specific object instance in hand. For hiding, the method invoked is determined at compile time based on the specific qualified name or method invocation expression used at the call site.
...
In this noncompliant example, the programmer attempts to override a static method but fails to understand that he has actually hidden the the static method has been hidden. Consequently, his code unexpectedly invokes the displayAccountStatus()
method of the superclass at two different call sites, rather than invoking the superclass method at one call site and the subclass method at the other. Additionally, his code uses expressions that are typical of dynamic dispatch, further indicating his confusion.
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");
}
}
|
...