Video in progress

What happens if you "override" a static method in a child class?

A static method can't be overridden; it is hidden (method hiding). Which version is called is decided at compile time by the declared type of the variable, not by the actual type of the object.

📖 Answer

class Parent {
    static String who() { return "Parent"; }
    String name() { return "Parent"; }
}
class Child extends Parent {
    static String who() { return "Child"; }      // hiding
    @Override String name() { return "Child"; }  // overriding
}

Parent p = new Child();
System.out.println(p.who());   // Parent: by the declared type
System.out.println(p.name());  // Child: by the actual object

The reason is simple: a static method belongs to the class, not to an object. Polymorphism doesn't apply to it.

Also:

  • if you put @Override on a static method, the compiler gives an error, which is a useful check;
  • "hiding" an instance method with a static one, or the other way around, is a compile error;
  • calling a static method through an object, like p.who(), is confusing, and the IDE warns about it too. Always write Parent.who().