Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Functional Interface in Java with Example

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:

@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:

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:

Doing something!

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.



This post first appeared on Javac, please read the originial post: here

Share the post

Functional Interface in Java with Example

×

Subscribe to Javac

Get updates delivered right to your inbox!

Thank you for your subscription

×