Static Methods in Java: Overriding vs. Hiding Explained

Answered using GPT-4o-mini by Java Q&A Hub

Question:

Can static methods be overridden In Java? why?

Answer:

In Java, static methods cannot be overridden in the same way that instance methods can. This is due to the way method resolution works in Java.

Explanation:

  1. Static Method Binding: Static methods are bound at compile time, which means that the method to be called is determined by the reference type, not the object type. When you call a static method, the Java compiler looks at the reference type to determine which method to execute.

  2. No Polymorphism: Since static methods are not associated with an instance of a class, they do not participate in polymorphism. This means that if you have a static method in a superclass and a static method with the same name in a subclass, the method in the subclass does not override the method in the superclass; instead, it hides it.

  3. Method Hiding: When a subclass defines a static method with the same name and parameters as a static method in its superclass, the subclass method is said to "hide" the superclass method. The method that gets called is determined by the reference type, not the object type.

Example:

class Parent {
    static void staticMethod() {
        System.out.println("Static method in Parent");
    }
}

class Child extends Parent {
    static void staticMethod() {
        System.out.println("Static method in Child");
    }
}

public class Main {
    public static void main(String[] args) {
        Parent parent = new Parent();
        Parent childAsParent = new Child();
        Child child = new Child();

        parent.staticMethod(); // Output: Static method in Parent
        childAsParent.staticMethod(); // Output: Static method in Parent (not Child)
        child.staticMethod(); // Output: Static method in Child
    }
}

Summary:

  • Static methods cannot be overridden; they can only be hidden.
  • The method that gets executed is determined by the reference type, not the actual object type.
  • This behavior is a result of static methods being resolved at compile time rather than at runtime.