No, we can not override static method in java. Static methods are those which can be called without creating object of class,they are class level methods.
On other hand,If subclass is having same method signature as base class then it is known as method overriding. Its execution decided at run time.
Below are the reasons why we can’t override static method in java:-
- Static methods are those which belong to the class.They do not belong to the object and in overriding, object decides which method is to be called.
- Method overriding occurs dynamically(run time) that means which method is to be executed decided at run time according to object used for calling while static methods are looked up statically(compile time).
public static void hello() //static method
class DisplayMessage extends Display
public static void hello() //redefining of base class static method in derived class
public class DisplayMsg
public static void main(String args)
Display d=new Display(); //creation of base class object
//base class reference is referring to derived class object and as per overriding rules it should call DisplayMessage hello()
d.hello(); //but it calls Display class hello()
DisplayMessage ds=new DisplayMessage(); //creation of derived class object
When you run above program, you will get below output.
As per the rules of method overriding, method call is resolved at run time by the type of object.So, in our above example d.hello() in second example should call hello() method of DisplayMessage class because reference variable of Display class is referring an object of DisplayMessage but it call Display class hello() itself.This happens because static method is resolved at compile time.
So If derived class’s static method have same signature as base class’s static method, it is called method hiding not method overriding.