Can we overload or override a static method in Java?

Object Oriented ProgrammingJava8Java Programming

If a class has multiple functions by the same name but different parameters, it is known as Method Overloading. If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding. Method overloading increases the readability of the program. Method overriding provides the specific implementation of the method that is already provided by its superclass parameter must be different in case of overloading, the parameter must be same in case of overriding.

Now considering the case of static methods, then static methods have following rules in terms of overloading and overriding.

  • Can be overloaded by another static method.

  • Can not be overridden by another static method in sub-class. The reason behind this is that sub-class only hides the static method but not overrides it.

Following example demonstrates the same.

Example

Live Demo

class SuperClass {
   public static void display() {
      System.out.println("SuperClass.display()");
   }

   //Method overloading of static method
   public static void display(int a) {
      System.out.println("SuperClass.display(int): " + a);
   }
}

class SubClass extends SuperClass {
   //Not method overriding but hiding
   public static void display() {
      System.out.println("SubClass.display()");
   }
}

public class Tester {
   public static void main(String[] args) {
      SuperClass object = new SubClass();

      //SuperClass display method is called
      //although object is of SubClass.
      object.display();        
      object.display(1);    
   }
}

Output

SuperClass.display()
SuperClass.display(int): 1

Notes

  • The static method is resolved at compile time cannot be overridden by a subclass. An instance method is resolved at runtime can be overridden.

  • A static method can be overloaded.

raja
Published on 23-Jul-2018 12:36:58
Advertisements