Overload Or Override Static Methods in Java

If I talk about Overload Or Override a Static Methods in java, we need to remember few points.

Points about  static method to remember :-

  1. Static Method Belongs to class not Object.
  2. A static method can be accessed directly by the class name and doesn’t need any object

Can We OverLoad Static Methods In Java:-

The Answer is “Yes”. If we talk about Overloading methods the concept is same in case of static methods as well. In order to overload static, we need to provide another static method with same name but different Signature. Let’s have a look at One example.

TestOverload.Java

Output:-

 

Whereas if we remove static keyword from one of the method, this is not overloading.For Example, let’s look at following code.

Output:-

This Will throw Compilation issue.

Can we Override Static Methods in Java:-

Overriding depends on having an instance of a class. The point of polymorphism is that you can subclass a class and the objects implementing those subclasses will have different behaviors for the same methods defined in the superclass. A static method is not associated with any instance of a class, hence answer is “NO”.

As you ca see in the example we have One Static method in base and derived class .Hence We might think its method Overloading , but its is not .

Output:-

Once we call obj.display()  , its is Method Hiding . Subclass has defined a class method with the same signature as a class method in the superclass. In that case the method of superclass is hidden by the subclass.Here the version of a method that is executed will NOT be determined by the object that is used to invoke it. In fact, it will be determined by the type of reference variable used to invoke the method. Interviewers may confuse you a lot on this topic if you are a beginner.

 

Related Posts:

Custom Class Loaders In java

Internal Working Of Class Loaders In java

Rest Service Using Spring Boot

, , ,

2 thoughts on “Overload Or Override Static Methods in Java

Leave a Reply

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