Skip to content

What Are Functional Interfaces in Java? With Examples

This is the introductory lesson on functional interfaces. Introduced in Java SE 8, these are powerful and most useful as either lambdas or method reference can use it.

Gopi Gorantala
Gopi Gorantala
2 min read

Table of Contents

Before Java 8

Interfaces are known for the following facts before Java 8.

  • There were no restrictions on abstract methods that should be declared in an interface.
  • The interface should not contain default and static methods, etc.

Introduction

A functional interface in Java has only one abstract method, called the functional method. Functional interfaces are also known as Single Abstract Method (SAM) interfaces.

Functional interfaces are used in Java to represent a single unit of behavior that a lambda expression or method reference can implement. Lambda expressions are a new feature in Java 8 that allows you to write concise code to represent a behavior as a method. A functional interface is required to use a lambda expression in Java.

Functional interfaces are a concept introduced in Java 8. There are two new packages that got added in Java 8 are

  1. java.util.function - Function API
  2. java.util.stream - Stream API

You might be thinking we already know what an interface is. So what makes normal interface and functional interface different, and what problems are they here to solve in Java, where normal interfaces fall short?

Isn’t this the right question we should ask ourselves?

Yes, when the Java team started adding functional interfaces to Java, they thought to do this to solve specific problems or use cases. Let us deep-dive into functional interfaces, lambdas, and much more. 🤩

What is a functional interface?

A functional interface (@FunctionalInterface) is a concept introduced in Java 8. Many enhancements and additional features are added to the JDK.

Functional Interface clearly says it should have

  1. Only one abstract method
  2. Any number of static methods are allowed (optional).
  3. Any number of default methods are allowed (optional).
These functional interfaces we declare in our application help us write Lambda expressions, which is a way of writing functional programming in Java.

Here are two simple examples of a functional interface:

Example 1:

@FunctionalInterface
public interface MyFunctionalInterface {
    public void doSomething();
}

In this example, MyFunctionalInterface is a functional interface because it has only one abstract method, doSomething(). The @FunctionalInterface annotation is optional but is a good practice to indicate that the interface is intended to be functional.

Example 2:

@FunctionalInterface
public interface Course {
    void printCourse(String courseTitle);

    default void defaultMethod() {
        System.out.println("This is a default method!");
    }
}

When defining a custom functional interface, we can add @FunctionalInterface annotation to explicitly say that this is a functional interface rather than just an interface.

This has no special effect, but a compiler error will be generated if this annotation is applied to an interface that is not functional, thus as a reminder that the interface should not be changed.

Let us see a simple example of printing a text on the console by writing our own custom functional interfaces.

@FunctionalInterface
public interface Logger {
  void logMessage(String message);
}
public class LoggerImpl implements Logger{
    
  @Override
  public void logMessage(String message) {
    System.out.println(message);
  }
}
public class MainApplication {
  public static void main(String[] args) {
    logger(new LoggerImpl());
  }
  
  public static void logger(Logger logger) {
    logger.logMessage("A message is sent");
  }
}

Conclusion

Functional interfaces can be used in various scenarios in Java, such as sorting and filtering collections, running background tasks, and handling events. Some examples of built-in functional interfaces in Java include Predicate, Consumer, Function, Supplier, and UnaryOperator.

Functional interfaces are an important feature of Java because they enable lambda expressions, which provide a concise and expressive way to represent behaviors as methods. They also help to make code more modular, reusable, and maintainable.

Java Streams APIJava

Gopi Gorantala Twitter

Gopi is an engineering leader with 12+ of experience in full-stack development—a specialist in Java technology stack. He worked for multiple startups, the European govt, and FAANG in India and Europe.

Comments


Related Posts

Members Public

Differences Between JDK, JRE, and JVM?

Short answer JDK, JRE, and JVM are essential components of the Java platform, each serving a distinct purpose. Here are the key differences between them: 1. JDK (Java Development Kit): The JDK is used by developers to write, compile, and debug Java code. 2. JRE (Java Runtime Environment): End-users use

Members Public

Difference Between String and char[] in Java

Short answer Strings String is an object with many helpful methods. String class in Java's standard library is designed to handle text as a sequence of characters. A string of characters (string object) is non-modifiable or immutable in Java. Once you've created it, you cannot modify

Members Public

What is an Object class in Java?

Short answer Object class is the super class of every class you can create. In Java, a class extends another class using the keyword extends. If you don't have any other class to extend, that's fine. The compiler will make your class extend the Object class.