How to Implement Functional Interfaces in Java 8

  • google plus

In Brief...

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.

Take our Introduction to Java Training course for free.

See the Course Outline and Register

Instructions

  1. First you will code the interface. In your text editor, type in the following Java statements:
    Functional Interface
    The 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

Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

Discuss