Can We Override Static Method in Java

One of the common Java interview questions is, Can We Override Static Method in Java?

The Answer is NO, We can’t Override the static function in Java. But we can Overload the Static Method in Java. Now the new question

Now the new question raised by interviewer Why? Why you can’t override but overload the Static method. We have already learned it earlier in Difference in Static and Dynamic Binding tutorial.

Static method is bonded during compile time using Type of reference variable and not Object. As per Java coding convention, static methods should be accessed by class name rather than the object. In short Static method can be overloaded, but can not be overridden in Java.

What is Method Hiding in Java?

If we declare,  another static method with the same signature in derived class(Child Class) than the static method of super class will be hidden, and any call to that static method in subclass will go to the static method declared in that class itself. This is known as method hiding in Java.


Override Static Method in Java

Let’s see an example of trying to override a static method.

Let’s create two Java Classes named ParentClass and ChildClass and establish the parent Child relationship. Now declare a common Static method named “printMe()”.

Now create another class and call the printMe() method of both classes.

Now as per method overriding; if a method is overridden then a call is resolved by type of object during runtime.
Which means, in our test class OverrideStatic, PClass.printMe(); should call Child class’ printMe() method, because reference variable of type Parent is referring an object of Child, but instead it call printMe()() method of Parent class itself.

This happens, because static methods are resolved or bonded during compile time, and only information which is available, and used by the compiler is the type of reference variable. Since PClass was reference variable of the Parent type, printMe() method from Parent class was called.

Now, In order to prove that static method can be hidden, if we call ChildClass.printMe() or cClass.printMe(), it will call printMe() method fromChild class.

This means static methods can not overridden in Java, they can only be hidden.
This also answers, Why static method can not be overridden in Java, because they are resolved during compile time. By the way, this example doesn’t show, whether you can overload static method or not, but you can.

0 Comment

Leave a Reply