How to Implement Functional Interfaces in Java 8

See Java: Tips and Tricks for similar articles.

Single abstract method interfaces are well-known to Java developers. For example, the Runnable interface contains one abstract method called run. In Java 8, single abstract method interfaces are known as functional interfaces. The benefit of a functional interface is that a developer can specify an anonymous implementation wherever a reference to the interface is required (for example, passing an implementation of the Runnable interface when instantiating a Thread object). In this tutorial, we'll create a functional interface that contains one abstract method to generate a greeting.

  1. First you will code the interface. In your text editor, type in the following Java statements:Functional InterfaceThe interface defines one method to return a greeting.
  2. Save your file as FunctionalInterface.java.
  3. Open a command prompt and navigate to the directory containing your Java interface. Then type in the command to compile the source and hit Enter.Compile Source for Functional Interface
  4. Now you will create the program that contains two anonymous implementations of the functional interface. Type in the following Java statements:Java Source for Test Functional Interface
  5. Save your file as UseFunctionalInterface.java.
  6. Return to the command prompt. Then type in the command to compile the source and hit Enter.Compile Source for Test Functional Interface
  7. Now type in the command to run your program and hit Enter. The output displays two greetings; one from each anonymous implementation of the functional interface.Run Test Functional Interface