To create a functional interface

You may come across codes like this ()->{ System.out.println("Hello World"); }, a bracket first then follow by an arrow, if you have ever written JavaScript before, it is known as arrow function in JavaScript. In Java land this is known as functional interface.

To create a functional interface, all you have to do is create an interface with a SAM(Single Abstract Method), and then put a @FunctionalInterface annotation to the interface.

SimpleFuncInterface.java
@FunctionalInterface
public interface SimpleFuncInterface {
  public void execute();
}

To implement Functional Interface

SimpleFunInterfaceTest.java
/*
* Implementing the interface by creating an
* anonymous inner class versus using 
* lambda expression.
*/
public class SimpleFunInterfaceTest {
  public static void main(String[] args) {
    carryOutWork(new SimpleFuncInterface() {
      @Override
      public void execute() {
        System.out.println("Do work in SimpleFun impl...");
      }
    });
    carryOutWork(() -> System.out.println("Do work in lambda exp impl..."));
  }
  public static void carryOutWork(SimpleFuncInterface sfi){
    sfi.execute();
  }
}
Output:
Do work in SimpleFun impl...
Do work in lambda exp impl...
Last modified: August 2, 2018

Author