How do Java 8 default methods hеlp with lambdas?
To give you an example take the case of the Collection.forEach
method, which is designed to take an instance of the Consumer
functional interface and has a default implementation in the Collection
interface:
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
If the JDK designers didn't introduce the concept of default methods then all the implementing classes of the Collection
interface would have to implement the forEach
method so it would be problematic to switch to Java - 8 without breaking your code.
So to facilitate the adoption of lambdas and the use of the new functional interfaces like Consumer
, Supplier
, Predicate
, etc. the JDK designers introduced the concept of default methods to provide backward compatibility and it is now easier to switch to Java - 8 without making any changes.
If you don't like the default implementation in the interface you can override it and supply your own.
They helped indirectly: you can use lambdas on collections thanks to additional methods like removeIf()
, stream()
, etc.
Those methods couldn't have been added to collections without completely breaking existing collection implementations if they had not been added as default methods.
Another situation where default methods help a ton is in the functional interfaces themself. Take the Function<T,R>
interface for example, the only method you really care about is R apply(T t)
, so when you need a Function
somewhere, you can pass a lambda and it will create a Function
instance where that lambda method is the apply
method.
However once you have a Function
instance, you can call other useful methods like <V> Function<T,V> andThen(Function<? super R,? extends V> after)
that combine functions on them. The default implementation is simply chaining the functions, but you can override it if you create your own class implementing the Function
interface.
In short, default methods give you an easy way to create lambdas from functional interfaces that have additinal methods, while giving you the option to override those additinal methods in with a full class if you need to.