Can we override static method in java

Can we override static method in java? This is an interview question asked frequently to junior level developers. So this time we can try this out and reach to an answer.

The one word answer to this question is No.

why? what happens if we create a method with same signature and return type in the subclass and both these methods(ie. method in super class and method in subclass) are static?
Yes this is possible, the program runs correctly without any compilation error.

Ok; before going into that details we can try an example and see what happens. So we are going to create a class with two methods out of which one method is static and other is non static; as given below.

Lets extend this class and override the method getName and getIdas given below.

You may have noted that adding @Override annotation to the method getId in the class Developer makes compilation error. So we can remove that annotation as above.
Now we can create another class which can call these methods in the above classes. It is given below.

As you can see above, we created an object of class Developer and assigned to super class Employee so that the variable myInstance is “a type” of Employee and it holds an object of Developer. Now run the class Main and see the output as follows.

You can see that the non static method getName is invoked from the subclass Developer while static method getId is invoked from superclass Employee itself.

Method hiding

In the previous example we saw that static method isĀ invoked from Super class. More generally we can say that static methods are invoked from type of reference variable. In the previous example type of reference variable myInstance was Employee and object of reference variable myInstance was Developer. This process is called Method hiding.

Why method hiding?

Because static method are binded at compile time and they are binded to the type of reference variable they have.

To summarize all we can take the following table from javadoc.

Defining a Method with the Same Signature as a Superclass’s Method
Superclass Instance Method Superclass Static Method
Subclass Instance Method Overrides Generates a compile-time error
Subclass Static Method Generates a compile-time error Hides

Leave a Comment

Your email address will not be published. Required fields are marked *