Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 892
Adolis Pali Avatar asked May 22 '26 03:05

Adolis Pali


1 Answers

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.

like image 85
JustAnotherDeveloper Avatar answered May 23 '26 18:05

JustAnotherDeveloper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!