It is claimed in this article that:
one of the major reasons for introducing
default
methods in interfaces is to enhance the Collections API in Java 8 to support lambda expressions.
I could understand that the @FunctionalInterface
helped by saying that there is ONLY one abstract method and the lambda should represent this particular method.
But how is it that the default
methods helped to support lambdas?
Default methods can be accessed only with object references, if you want to access default method you'd have an object reference of Functional Interface, in lambda expression method body you won't have so can't access it.
A default method cannot override a method from java.
Java 8 introduces default method so that List/Collection interface can have a default implementation of forEach method, and the class implementing these interfaces need not implement the same.
You can define a lambda expression that would represent an A instance regardless of the context you are in. It can be a static interface method, it could be a default interface method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With