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

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

    when should interface with default methods be used and when should an abstract class be used?

    Backward compatibility: Imagine that your interface is implemented by hundreds of classes, modifying that interface will force all the users to implement the newly added method, even though it could be not essential for many other classes that implements your interface, Plus it allows your interface to be a functional interface

    Facts & Restrictions:

    1-May only be declared within an interface and not within a class or abstract class.

    2-Must provide a body

    3-It is not assumed to be abstract as other normal methods used in an interface.

    0 讨论(0)
  • 2020-11-22 07:40

    As described in this article,

    Abstract classes versus interfaces in Java 8

    After introducing Default Method, it seems that interfaces and abstract classes are same. However, they are still different concept in Java 8.

    Abstract class can define constructor. They are more structured and can have a state associated with them. While in contrast, default method can be implemented only in the terms of invoking other interface methods, with no reference to a particular implementation's state. Hence, both use for different purposes and choosing between two really depends on the scenario context.

    0 讨论(0)
  • 2020-11-22 07:40

    These two are quite different:

    Default methods are to add external functionality to existing classes without changing their state.

    And abstract classes are a normal type of inheritance, they are normal classes which are intended to be extended.

    0 讨论(0)
提交回复
热议问题