Hiding vs Overriding: Static Method Behavior
What you'll learn: Why static methods behave fundamentally differently from instance methods when redefined in subclasses.
The Core Difference
When you define a method with the same signature in a subclass, the behavior depends on whether it's static or instance:
- Instance methods are overridden — the JVM uses the actual object's type at runtime to decide which version to call (dynamic dispatch)
- Static methods are hidden — the compiler uses the reference type at compile time to decide which version to call (static binding)
Static methods belong to the class itself, not to any instance. Since there's no object whose runtime type can be checked, dynamic dispatch doesn't apply. The method is resolved purely based on what type the reference variable is declared as.
Why This Matters
class Parent {
static void greet() {
System.out.println("Hello from Parent");
}
}
class Child extends Parent {
static void greet() {
System.out.println("Hello from Child");
}
}
Parent ref = new Child();
ref.greet(); // Prints: "Hello from Parent"
Even though ref points to a Child object at runtime, the static method is chosen based on the reference type (Parent), not the object type. This is hiding, not overriding.
Think of It This Way
Instance methods are like asking "What can this object do?" — the answer depends on what the object actually is.
Static methods are like asking "What does this class provide?" — the answer depends on which class name you're asking through.
Key Takeaway:
Static methods are hidden by subclass definitions and resolved at compile time based on reference type, while instance methods are overridden and resolved at runtime based on the actual object type.