Adolis Pali
Adolis Pali

Reputation: 339

Why can I override a static interface method?

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
}

Upvotes: 9

Views: 6183

Answers (1)

JustAnotherDeveloper
JustAnotherDeveloper

Reputation: 2256

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.

Upvotes: 10

Related Questions