Can we override static methods in Java?

Static methods cannot be overridden in Java because overriding relies on runtime polymorphism, whereas static methods are resolved at compile time. If a subclass declares a static method with the same signature as a static method in the parent class, it is called method hiding, not method overriding.

Key Points: • Static methods belong to the class, not to individual objects. • Method overriding requires runtime method resolution based on the actual object type. • Static methods are resolved by the compiler using the reference type. • Defining a static method with the same signature in a subclass hides the parent method. • This behavior is known as method hiding, not overriding.

Example: A child class can declare a static method with the same name as the parent class, but the method called depends on the reference type, not the object type.

Code Example:

class Parent {

    static void display() {
        System.out.println("Parent Static Method");
    }
}

class Child extends Parent {

    static void display() {
        System.out.println("Child Static Method");
    }
}

public class Demo {

    public static void main(String[] args) {

        Parent parent = new Child();

        parent.display();
    }
}

Output:

Parent Static Method

Why Does This Happen?

The reference variable is of type Parent:

Parent parent = new Child();

Since display() is static, Java determines which method to call using the reference type (Parent) during compilation.

Method Hiding vs Method Overriding:

Method Hiding: • Applies to static methods • Resolved at compile time • Depends on reference type

Method Overriding: • Applies to instance methods • Resolved at runtime • Depends on actual object type

Example of True Overriding:

class Parent {

    void display() {
        System.out.println("Parent Method");
    }
}

class Child extends Parent {

    @Override
    void display() {
        System.out.println("Child Method");
    }
}

Parent parent = new Child();

parent.display();

Output:

Child Method

This is runtime polymorphism because the instance method is overridden.

Interview Tip: A concise interview answer is:

"No, static methods cannot be overridden because they belong to the class and are resolved at compile time. If a subclass defines a static method with the same signature as its parent, it hides the parent method rather than overriding it. This behavior is called method hiding."