Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do Java 8 default methods hеlp with lambdas?

Tags:

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?

like image 682
mCs Avatar asked Apr 21 '19 07:04

mCs


People also ask

Can we use default method in lambda expression?

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.

Can default methods be overridden in Java 8?

A default method cannot override a method from java.

What is the default method in Java 8?

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.

Can lambda expressions be used to implement interfaces having default and static methods?

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.


2 Answers

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.

like image 152
Fullstack Guy Avatar answered Oct 04 '22 20:10

Fullstack Guy


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.

like image 33
JB Nizet Avatar answered Oct 04 '22 19:10

JB Nizet