5

I can't find any good source explaining why:

abstract class AA {
    public static void log() {}
}

class BB extends AA {
    public void log() {} //error
}
interface CC {
    public static void log() {}
}

class DD implements CC {
    public void log() {} //Ok
}
akuzminykh
  • 4,522
  • 4
  • 15
  • 36
Adolis Pali
  • 149
  • 1
  • 7
  • Also https://stackoverflow.com/questions/2475259/can-i-override-and-overload-static-methods-in-java and https://stackoverflow.com/questions/2831426/is-it-possible-to-override-a-static-method-in-derived-class – Zoe Sep 14 '20 at 08:15
  • The static method on the interface is completely unrelated to any class that implements the interface. Classes implementing the interface know nothing of the interface (except for default methods). – Scratte Sep 14 '20 at 16:17

1 Answers1

9

If a subclass defines a static method with the same signature as another static method in its parent class, then the method in the subclass hides the one in the superclass. This is distinct from overriding an instance method in two ways:

  • When you override an instance method and invoke it, you invoke the one in the subclass.
  • When you do the same for a static method, the invoked version depends on from which class you invoke it.

As for interfaces, static methods in interfaces are not inherited. Therefore it's technically not an override. In your example, you could call log() from class DD, or you could call log() from interface CC (in which case you'd need to call it using the name of the interface: CC.log()). They are separate methods.

This is a good resource on overriding methods that covers both static and instance methods in classes, and static methods in interfaces.

JustAnotherDeveloper
  • 2,061
  • 2
  • 10
  • 24