In Java, a functional interface is an interface that has only one abstract method. It is also called a Single Abstract Method (SAM) interface. Functional interfaces are used to implement lambda expressions and method references.
Functional interfaces have a special annotation called @FunctionalInterface. This annotation ensures that the interface has only one abstract method. If you try to add another abstract method to the interface, the compiler will generate an error.
Here is an example of a functional interface:
@FunctionalInterface
interface MyInterface {
void myMethod();
}
In this example, the MyInterface interface has only one abstract method called myMethod(). The @FunctionalInterface annotation ensures that this interface is a functional interface.
Functional interfaces can be used to create lambda expressions, which are anonymous methods. Here is an example of how to create a lambda expression using the MyInterface functional interface:
MyInterface myInterface = () -> System.out.println("Hello World");
myInterface.myMethod(); // prints "Hello World"
In this example, the lambda expression
() -> System.out.println("Hello World")
implements the MyInterface interface. The myMethod() method is called on the myInterface object, which executes the lambda expression and prints "Hello World" to the console.
Functional interfaces can also be used with method references. Here is an example of how to use a method reference with the MyInterface functional interface:
public class MyClass {
public static void myMethod() {
System.out.println("Hello World");
}
}
MyInterface myInterface = MyClass::myMethod;
myInterface.myMethod(); // prints "Hello World"
In this example, the myMethod() method of the MyClass class is a static method that takes no arguments. The MyInterface functional interface has only one abstract method that takes no arguments. The myInterface object is created using a method reference to the MyClass::myMethod method. The myMethod() method is called on the myInterface object, which executes the myMethod() method of the MyClass class and prints "Hello World" to the console.
In summary, a functional interface is an interface that has only one abstract method. It is used to implement lambda expressions and method references. The @FunctionalInterface annotation is used to ensure that an interface is a functional interface.