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

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 20-Jan-2020 14:33:03
Advertisements