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 |
|
1 |
|
Simply calling static method is easy to understand:
1 |
|
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 |
|
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 |
|
1 |
|
In class B
, overriding occurs, and the result of running myMethod
would be different:
1 |
|
There is also no warning anymore.
Remark
Same as preventing from overriding, add keyword final
can also prevent a static
method from hiding.