Can you override static methods in Java? Why or why not?
No, static methods cannot be overridden in Java.
Reason: Static Methods Belong to the Class
Static methods are associated with the class itself, not with any specific instance of the class. Since method overriding is based on runtime polymorphism (which relies on object instances), static methods are not eligible for overriding.
In overriding, the method call is resolved based on the actual object type at runtime. However, for static methods, the method call is resolved at compile time, based on the reference type, making overriding irrelevant.
What Happens if You Override a Static Method?
If you declare a static method in a subclass with the same name and parameters as a static method in the parent class, it is called method hiding, not overriding.
Example:
class Parent {
static void display() {
System.out.println("Static method in Parent class");
}
}
class Child extends Parent {
static void display() {
System.out.println("Static method in Child class");
}
}
public class Main {
public static void main(String[] args) {
Parent parent = new Parent();
Parent child = new Child(); // Reference type is Parent, object type is Child
parent.display(); // Calls Parent's display
child.display(); // Still calls Parent's display because static methods are resolved at compile time
}
}
Output:
Static method in Parent class
Static method in Parent class
In this case:
- The method call is determined by the reference type, not the object type.
- The Child class’s static display() method hides the Parent class’s method.
Key Points to Remember
-
Static methods cannot be overridden, only hidden.
-
Hiding static methods breaks runtime polymorphism, as the method call depends on the reference type.
-
Overriding requires an instance, but static methods are not tied to instances.