Functional Interfaces
In Java 8, the concept of functional interfaces was introduced to support lambda expressions. A functional interface is an interface that contains only one abstract method. The @FunctionalInterface annotation is used to indicate that an interface is intended to be functional.
Functional interfaces play a crucial role in lambda expressions because they allow lambda expressions to be bound to them. By implementing a functional interface, you can define the behavior of the lambda expressions.
Here is an example of a functional interface:
1@FunctionalInterface
2interface FunctionalInterface {
3 void execute();
4}In this example, the FunctionalInterface defines a single abstract method execute(). Any lambda expression that matches the signature of this method can be used as an instance of the FunctionalInterface.
To use a functional interface and its corresponding lambda expression, you can write code like this:
1FunctionalInterface fi = () -> {
2 // Code block
3};
4fi.execute();In this code, we declare an instance of the FunctionalInterface and assign a lambda expression to it. The lambda expression represents the implementation of the execute() method.
Functional interfaces are widely used in Java 8 features such as the Stream API and the forEach method of the Iterable interface. They provide a powerful mechanism for defining behavior in a concise and expressive way, making your code more readable and maintainable.
xxxxxxxxxxclass Main { public static void main(String[] args) { // replace with your Java logic here FunctionalInterface fi = () -> { // Code block }; fi.execute(); }}


