Can we override static method in java

Previous
Next

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).

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.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog