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

后端 未结 15 1763
闹比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:22

    Regarding your query of

    So when should interface with default methods be used and when should an abstract class be used? Are the abstract classes still useful in that scenario?

    java documentation provides perfect answer.

    Abstract Classes Compared to Interfaces:

    Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation.

    However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods.

    With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public. In addition, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces.

    Use cases for each of them have been explained in below SE post:

    What is the difference between an interface and abstract class?

    Are the abstract classes still useful in that scenario?

    Yes. They are still useful. They can contain non-static, non-final methods and attributes (protected, private in addition to public), which is not possible even with Java-8 interfaces.

提交回复
热议问题