Wiki Markup |
---|
When a class declares a static method _m_, the declaration of _m_ hides any method _m'_, where the signature of _m_ is a subsignature of the signature of _m'_ and the declaration of _m'_ is both in the superclasses and superinterfaces of the declaring class and also would otherwise be accessible to code in the declaring class \[[JLS 2005|AA. Bibliography#JLS 05]\] ["8.4.8.2 Hiding (by Class Methods)"|http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.4.8.2]. |
...
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");
}
}
|
Compliant Solution
In this compliant solution, the programmer declares the displayAccountStatus()
methods as instance methods, by removing the static
keyword. Consequently, the dynamic dispatch at the call sites produces the expected result. The @Override
annotation indicates intentional overriding of the parent method.
Code Block |
---|
|
class GrantAccess {
public void displayAccountStatus() {
System.out.print("Account details for admin: XX");
}
}
class GrantUserAccess extends GrantAccess {
@Override
public 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");
}
}
|
Wiki Markup |
---|
The methods inherited from the superclass can also be overloaded in a subclass. Overloaded methods are new methods, unique to the subclass and neither hide nor override the superclass method \[[Tutorials 2008|AA. Bibliography#Tutorials 08]\]. |
Wiki Markup |
---|
Technically, a private method cannot be hidden or overridden. There is no requirement that private methods with the same signature in the subclass and the superclass, bear any relationship in terms of having the same return type or {{throws}} clause, the necessary conditions for hiding \[[JLS 2005|AA. Bibliography#JLS 05]\]. Consequently, hiding cannot occur when the methods have different return types or {{throws}} clauses. |
...