When to use: Java 8+ interface default method, vs. abstract method

后端 未结 15 1970
闹比i
闹比i 2020-11-22 07:01

Java 8 allows for default implementation of methods in interfaces called Default Methods.

I am confused between when would I use that sort of interface default

15条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 07:38

    Default methods in Java interface enables interface evolution.

    Given an existing interface, if you wish to add a method to it without breaking the binary compatibility with older versions of the interface, you have two options at hands: add a default or a static method. Indeed, any abstract method added to the interface would have to be impleted by the classes or interfaces implementing this interface.

    A static method is unique to a class. A default method is unique to an instance of the class.

    If you add a default method to an existing interface, classes and interfaces which implement this interface do not need to implement it. They can

    • implement the default method, and it overrides the implementation in implemented interface.
    • re-declare the method (without implementation) which makes it abstract.
    • do nothing (then the default method from implemented interface is simply inherited).

    More on the topic here.

提交回复
热议问题