How to Implement Functional Interfaces in Java 8
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.
- First you will code the interface. In your text editor, type in the following Java statements:
The interface defines one method to return a greeting.
- Save your file as FunctionalInterface.java.
- 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.
- Now you will create the program that contains two anonymous implementations of the functional interface. Type in the following Java statements:
- Save your file as UseFunctionalInterface.java.
- Return to the command prompt. Then type in the command to compile the source and hit Enter.
- 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.