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).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package org.arpit.java2blog; class Display { public static void hello() //static method { System.out.println("Hello...Good morning"); } } class DisplayMessage extends Display { public static void hello() //redefining of base class static method in derived class { System.out.println("Hello...everyone"); } } public class DisplayMsg { public static void main(String args[]) { Display d=new Display(); //creation of base class object d.hello(); d=new DisplayMessage(); //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 ds.hello(); } } |
When you run above program, you will get below output.
Output:
Hello…Good morning
Hello…Good morning
Hello…everyone
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.