implements an interface must provide an implementation for each method defined by the
interface or inherit the implementation from a superclass. But this causes a problem when
library designers need to update an interface to add a new method.
Existing concrete classes (which may not be under their control) need to be modified to reflect the new interface
contract. This is particularly problematic because the Java 8 API introduces many new methods
on existing interfaces.
For Example Java collections library has been designed many years ago, and there is a
problem,if the Collection interface gets new methods, such as forEach, then
every program that defines its own class implementing Collection will break until
it, too, implements that method. That is simply unacceptable in Java.
Default methods are added to Java 8 largely to support library designers by enabling them to write more evolvable interfaces.
The Java designers decided to solve this problem once and for all by allowing
interface methods with concrete implementations (called default methods).
Those methods can be safely added to existing interfaces.
Now with help of default methods we you can just implement the methods in the interface.
Interfaces in Java 8 can now declare methods with implementation code; this
can happen in two ways.
a) Java 8 allows static methods inside interfaces.
b) Java 8introduces a new feature called default methods that allows you to provide a default
implementation for methods in an interface. In other words, interfaces can provide concrete
implementation for methods.
As a result, existing classes implementing an interface will automatically inherit the default implementations if they don’t provide one explicitly.
0 Comments