In the last article in this series, we discussed what lambda expressions are and how to write lambda expressions. In this article, we will discuss how to execute lambda expressions. As I said, at the end of the last article, we can use the new features of Java 8 to execute lambda expressions, functional interfaces .
So what is functional interface?
The interface containing the single abstract 方法(SAM) are called Functional 接口。 Some of the Functional 接口 we may know are:
Interface | method |
---|---|
Operable | run() |
Recallable | call() |
comparable | compared to() |
Action listener | actionPerformed() |
In version 1.8, Java introduced a note @FunctionalInterface
to explicitly specify the interface as a functional interface. But the comment is optional. However, it is recommended to write comments. It helps prevent any other abstract methods. If the annotated interface contains multiple abstract methods, then we will get a compile-time error, prompting:
error: Unexpected @FunctionalInterface annotation@FunctionalInterface^ CustomInterface is not a functional interface multiple non-overriding abstract methods found in interface CustomInterface
Note: The functional interface can have multiple default and static methods.
Example 1:
@FunctionalInterfaceinterface A {
void m1();
}
@FunctionalInterface
interface B extends A {
}
@FunctionalInterface
interface C extends A {
void m1();
}
@FunctionalInterface
interface D extends A {
void m2();
}
In the above example, the definition of interface D is invalid because it contains two methods: m1 () [extended from interface A] and m2 ().
In the next part, I will introduce how to use lambda expressions with functional interfaces.
from: https://dev.to//csangharsha/java-8-functional-interface-2cm9