A functional interface in Java is an interface with exactly one abstract method. It can be implemented using lambda expressions or method references, making it useful for functional programming.
Contain multiple default and static methods.
It can extend another interface if the resulting interface has only one abstract method.
Java
publicclassGeeks{publicstaticvoidmain(String[]args){// Pass a lambda expression to ThreadnewThread(()->System.out.println("New thread created")).start();}}
Output
New thread created
Explanation:
Runnable has one abstract method, run().
The lambda expression provides the implementation of run().
The lambda is passed to the Thread constructor, which accepts a Runnable.
Calling start() starts a new thread that executes the lambda body.
The @FunctionalInterface annotation is optional. It instructs the compiler to verify that the interface satisfies the functional interface requirements.
Rules of Functional Interfaces
A functional interface must have exactly one abstract method, excluding methods matching public methods of Object.
It can contain multiple default and static methods.
It can inherit methods from other interfaces if they do not introduce additional independent abstract methods.
The @FunctionalInterface annotation enables compile-time validation but is not required.
Example: Using @FunctionalInterface Annotation
Program to creates a functional interface to calculate the square of a number.
Java
@FunctionalInterfaceinterfaceSquare{intcalculate(intx);}classGeeks{publicstaticvoidmain(String[]args){// Implement the interface using a lambdaSquaresquare=x->x*x;System.out.println(square.calculate(5));}}
Output
25
Explanation:
Square declares one abstract method, calculate(int x).
The lambda expression implements this method.
calculate(5) returns 25.
Functional Interfaces Before Java 8
Functional interfaces existed before Java 8. However, developers commonly used anonymous inner classes to implement them. Java 8 introduced lambda expressions and method references, providing shorter alternatives.
Example: Using an Anonymous Inner Class
Java
classGeeks{publicstaticvoidmain(String[]args){// Implement Runnable using an anonymous classnewThread(newRunnable(){@Overridepublicvoidrun(){System.out.println("New thread created");}}).start();}}
Output
New thread created
The anonymous class implements run() explicitly. A lambda expression provides a shorter implementation for the same functional interface.
Types of Functional Interfaces
Java 8 introduced the java.util.function package with standard functional interfaces for common operations.