How to create our own/custom functional interface in Java?


The functional interface is a simple interface with only one abstract method. A lambda expression can be used through a functional interface in Java 8. We can declare our own/custom functional interface by defining the Single Abstract Method (SAM) in an interface.

Syntax

interface CustomInterface {
   // abtstact method
}

Example

@FunctionalInterface
interface CustomFunctionalInterface {
   void display();
}
public class FunctionInterfaceLambdaTest {
   public static void main(String args[]) {
      // Using Anonymous inner class
      CustomFunctionalInterface test1 = new CustomFunctionalInterface() {
         public void display() {
            System.out.println("Display using Anonymous inner class");
         }
      };
      test1.display();
      // Using Lambda Expression
      CustomFunctionalInterface test2 = () -> {    // lambda expression
         System.out.println("Display using Lambda Expression");
      };
      test2.display();
   }
}

Output

Display using Anonymous inner class
Display using Lambda Expression

Updated on: 14-Jul-2020

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements