Functional Interfaces and SAM-Types

In Java, a functional interface is an interface that has a single abstract method (also known as a SAM type, or Single Abstract Method type). Functional interfaces are used to represent function objects, or lambda expressions, which are anonymous functions that can be passed as arguments to other methods.

Here is an example of a functional interface in Java:

@FunctionalInterface
public interface Runnable {
  void run();
}

In this example, the Runnable interface is a functional interface because it has a single abstract method, run(), which takes no arguments and returns void.

Functional interfaces are often used in Java to specify the types of lambda expressions. For example, the Runnable interface can be used to specify a lambda expression that represents a piece of code that can be executed in a separate thread:

Runnable r = () -> {
  // code to be executed in a separate thread
};

In this example, the lambda expression () -> { /* code */ } is equivalent to an anonymous class that implements the run() method of the Runnable interface.

It's worth noting that functional interfaces are a key feature of the Java language and are widely used in Java 8 and later versions to support the implementation of functional programming techniques. There are many built-in functional interfaces in Java, such as Function, Consumer, and Predicate, as well as a number of additional interfaces in the java.util.function package.