Can we override the static method in Java?

No, you cannot override static method in Java because method overriding is based upon dynamic binding at runtime and static methods are bonded using static binding at compile time. Though you can declare a method with the same name and method signature in the subclass which does look like you can override static method in Java in reality that is method hiding. Java won't resolve method call at runtime and depending upon the type of object which is used to call the static method, the corresponding method will be called. It means if you use the Parent class's type to call a static method, original static will be called from a patent class, on the other hand, if you use Child class's type to call a static method, a method from child class will be called.

In brief, you can not override static methods in Java. If you use Java IDE like Eclipse or Netbeans, they will show a warning that the static method should be called using class name and not by using an object because static method can not be overridden in Java.

Overriding Static method in Java


/** * * Java program which demonstrate that we can not override static method in Java. * Had Static method can be overridden, with Super class type and sub class object * static method from sub class would be called in our example, which is not the case. * @author */ public class CanWeOverrideStaticMethod { public static void main(String args[]) { Screen scrn = new ColorScreen(); //if we can override static , this should call method from Child class scrn.show(); //IDE will show warning, static method should be called from classname } } class Screen{ /* * public static method which can not be overridden in Java */ public static void show(){ System.out.printf("Static method from parent class"); } } class ColorScreen extends Screen{ /* * static method of same name and method signature as existed in super * class, this is not method overriding instead this is called * method hiding in Java */ public static void show(){ System.err.println("Overridden static method in Child Class in Java"); } } Output: Static method from parent class

This output confirms that you can not override static method in Java and static method are bonded based upon type information and not based upon Object. had the Static method be overridden, a method from the Child class or ColorScreen would have been called.

That's all on discussion Can we override static method in Java or not. We have confirmed that no, we can not override static method, we can only hide the static method in Java. Creating a static method with the same name and method signature is called Method hiding in Java.