This tutorial explains what is a Functional Interface in Java and how to implement it using lambda expression.
This example demonstrates how functional interfaces can be used to pass behaviors as method arguments, making it possible to implement lambdas and method references in Java.
A functional interface in Java is an interface that has only one abstract method.
Java 8 introduced functional interfaces as a part of its support for functional programming.
The idea behind functional interfaces is to enable developers to pass behaviors (functions) as method arguments, making it possible to implement lambdas and method references in the Java language.
Here’s an example:
1 2 3 4 |
@FunctionalInterface public interface MyFunctionalInterface { void doSomething(); } |
In this example, the 'MyFunctionalInterface'
interface has only one abstract method, 'doSomething()'
. Because it has only one abstract method, it can be considered a functional interface.
Here’s an example of how you might use a functional interface to pass a behavior as a method argument:
1 2 3 4 5 6 7 8 9 10 |
public class Main { public static void main(String[] args) { MyFunctionalInterface task = () -> System.out.println("Doing something!"); execute(task); } public static void execute(MyFunctionalInterface task) { task.doSomething(); } } |
The output of this program would be:
In this example, the 'Main'
class declares a variable 'task'
of type 'MyFunctionalInterface'
. This variable is assigned a lambda expression that represents the behavior to be executed. The execute
method takes an instance of 'MyFunctionalInterface'
as an argument, and calls its 'doSomething()'
method.