Hide Superclass Static Methods in Java

Last updated on May 23, 2023 pm

Hide Superclass Static Methods in Java

A static method cannot be overridden in Java.

This is because the concept of method overriding is based on dynamic or late binding, which means the actual method to be executed is determined at runtime based on the type of the object. And a static method cannot show runtime polymorphism.

However, Java does accept a static method existing in subclass with same declaration signature to its superclass. It does not override the static method in the superclass. Instead, it hides the superclass method, meaning the subclass has its own separate static method with the same name.

Hiding

This could be seen with the following example:

1
2
3
4
5
public class A {
public static int myMethod(int x) {
return x + 2;
}
}
1
2
3
4
5
public class B extends A {
public static int myMethod(int x) {
return x * 2;
}
}

Simply calling static method is easy to understand:

1
2
A.myMethod(5); // 5 + 2 = 7
B.myMethod(5); // 5 * 2 = 10

The two methods exist peacefully. Inside the class B, the myMethod of class A is only hidden from the scope.

Another Perspective

Another way to check it out is like this:

1
2
3
4
5
6
7
8
A myInstance = new A();
myInstance.myMethod(5); // 5 + 2 = 7

myInstance = new B();
myInstance.myMethod(5); // 5 + 2 = 7

B anotherInstance = new B();
anotherInstance.myMethod(5); // 5 * 2 = 10

But note that access static method by instance is not a good practice. This is only for demonstration. Typically, it will cause a warning that The static method myMethod(int) from the type A should be accessed in a static way.

Overriding

Note how is this different from overriding.

For example, if both comment out the keyword static in class A and B,

1
2
3
4
5
public class A {
public /* static */ int myMethod(int x) {
return x + 2;
}
}
1
2
3
4
5
public class B extends A {
public /* static */ int myMethod(int x) {
return x * 2;
}
}

In class B, overriding occurs, and the result of running myMethod would be different:

1
2
3
4
5
6
7
8
A myInstance = new A();
myInstance.myMethod(5); // 5 + 2 = 7

myInstance = new B();
myInstance.myMethod(5); // 5 * 2 = 10

B anotherInstance = new B();
anotherInstance.myMethod(5); // 5 * 2 = 10

There is also no warning anymore.

Remark

Same as preventing from overriding, add keyword final can also prevent a static method from hiding.

References


Hide Superclass Static Methods in Java
https://lingkang.dev/2023/05/23/hide-static-java/
Author
Lingkang
Posted on
May 23, 2023
Licensed under