Can static, private and final methods be overridden in Java?
No. Final methods are forbidden from overriding, private methods are invisible to subclasses, and static methods belong to the class, so a same-named subclass method only hides the parent one instead of overriding it.
Explain it simply
Overriding means "when someone asks this object, it answers in its own way". A static method is not asked of an object at all, it is asked of the class name, so there is no object whose answer could change.
Example
class Parent {
static String who() { return "Parent"; }
private String secret() { return "p-secret"; }
final String id() { return "p-id"; }
}
class Child extends Parent {
static String who() { return "Child"; } // hides, not overrides
String secret() { return "c-secret"; } // new method, unrelated
// String id() { ... } // compile error: final
}
Parent p = new Child();
System.out.println(p.who()); // prints: Parent (decided by reference type)What to say in the interview
"A static method with the same signature in the child is method hiding: the call is resolved at compile time using the reference type, so a Parent reference calls Parent.who() even when it holds a Child. A private method is not inherited, so the child's method with the same name is a brand new method. A final method cannot be overridden and the compiler enforces it."
Common mistakes
- Putting
@Overrideon a static method. It gives a compile error. - Calling static methods through an instance, which hides the real behaviour.