Can we override a static method in Java?

Rony Emrul
Oct 30, 2020

In Java, we can declare a method with the same signature as it’s parent class. In another word, it’s called method overriding. But when it comes to the static method we, in fact, can do the same but it’s not called method overriding but method hiding. As we all know that static members are class level. So it’s gets decided at the creation of the class which method should be called.

In other words, Parent class methods that are static are not part of a child class (although they are accessible), so there is no question of overriding it. Even if you add another static method in a subclass, identical to the one in its parent class, this subclass static method is unique and distinct from the static method in its parent class.

This phenomenon is called method hiding not method overriding. In method overriding we get run time polymorphism. With method hiding we won’t get runtime polymorphism.

Output:
> static method from Parent
> overriden NON — Static method from child

In the above example, we called the staticMethod() with the parentClass reference. Since there is no runtime polymorphism parent class staticMethod() gets called.

--

--

Rony Emrul
Rony Emrul

Written by Rony Emrul

Backend Software Engineer, Technology Enthusiast

No responses yet