Need of default methods in Java
Traditionally, a Java interface groups related methods together into a contract.
Any (non abstract) class that implements an interface must provide an implementation for each method defined by the interface or inherit the implementation from a superclass.
But this requirement causes a problem when library designers need to update an interface to add a new method.
Indeed, existing concrete classes (which may not be under the interface designers’ control) need to be modified to reflect the new interface contract as shown below , we need to implement new method 2 in the concrete implementation.
This situation is particularly problematic because the Java 8 API introduces many new methods on existing interfaces, such as the sort method on the List interface that you used in previous chapters
Now all the concrete implementation need to provide the definition of sort() method, this is a breaking change.
Solution is the Default Methods:
In order to solve this problem Java 8 introduced a new mechanism to tackle this problem.
It may sound surprising, but since Java 8 interfaces can declare methods with implementation code in two ways.
First, Java 8 allowed static methods inside interfaces.
Second, Java 8 introduced a new feature called default methods that allows you to provide a default implementation for methods in an interface.
In other words, interfaces can now provide concrete implementation for methods. As a result, existing classes implementing an interface automatically inherit the default implementations if they don’t provide one explicitly, which allows you to evolve interfaces nonintrusively. You’ve been using several default methods all along. Two examples you’ve seen are sort in the List interface and stream in the Collection interface.
Please share and clap if you liked my content. Also consider supporting me if you want me to keep creating content.