Java 8: Functional Interfaces

Java 8: Functional Interfaces

·

3 min read

This article will introduce you to functional interfaces, why you need them, and how to create them.

Let's start.

What is a functional interface?

A functional interface is an interface that contains only a single abstract method (a method that doesn’t have a body). A functional interface can have any number of default methods.

What's the difference between a functional interface and an interface?

An interface is functional if it has only one abstract method. It may have default or static methods. Functional interfaces enable lambda expressions.

A Java interface instead represents the IS-A relationship. Yo use a Java interface to achieve abstraction, polymorphism and multiple inheritances.

Why do you need a functional interface?

You need a functional interface to use lambda expressions. Functional interfaces make the code more straightforward to read.

For example, an anonymous class is created like this:

public class AnonymousClass {

    public static void main(String[] args) {

        Thread thread = new Thread(){
            public void run(){
                System.out.println("Understanding what an anonymous class is.");
            }
        };
        thread.start();
    }
}

In the code above, you have used the Thread class to create an object and print out a message when we start the thread. The outcome is:

Understanding what is an anonymous class.

If instead, you use a functional interface, you can reduce the lines of code that you write and increase its readability.

public class AnonymousClassExample {

    public static void main(String[] args) {

        Runnable runnable = () -> {
            System.out.println("Understanding functional interfaces.");
        };
        runnable.run();
    }
}

The outcome is:

Understanding functional interfaces.

In short, the main benefit of using functional interfaces is that they can be instantiated using lambda expressions rather than lengthy anonymous classes.

How to create a functional Interface

You can either create your functional interface with the annotation @FunctionalInterface like in Example 1 or use the ones which have already been predefined by Java as seen in Example 2.

Example 1

  1. You create your interface called FunctionalInterface with a single abstract method and mark it with the annotation @ FunctionalInterface.

  2. You have a public class FunctionalInterfaceDemo where you want to execute the method.

  3. You use the lambda expression to represent the functional interface. You have two parameters because the method multiplyNumber() has two arguments. It can be read like this: "Given a parameter x and a parameter y, perform the multiplication between the two".

  4. You print out the multiplication between 2 and 3.

@java.lang.FunctionalInterface
interface FunctionalInterface{

   public int multiplyNumber(int x, int y);

}

public class FunctionalInterfaceDemo {

   public static void main(String[] args) {

       FunctionalInterface functionalInterface = (x, y) -> x * y;

       System.out.println("The result is: " functionalInterface.multiplyNumber(2, 3));
   }
}

The outcome is:

The result is: 6

Example 2

  1. You use the predefined functional interface ToDoubleFunction. This functional interface takes an argument T (in our case of type String) and returns a double as a result.

  2. Return the length of a given parameter.

  3. The ToDoubleFunction interface has a single abstract method, the applyAsDouble() method. In our case, it has the String "Hello Maddy" as a parameter.

  4. In the end, we print the length of the message, which is 12.0. Remember that spaces are included.

import java.util.function.ToDoubleFunction;
public class FunctionalInterfaceDemo {

    public static void main(String[] args) {

       ToDoubleFunction<String> length = x -> x.length();

        System.out.println(length.applyAsDouble("Hello Maddy!"));
    }
}

The outcome is:

12.0

Notes:

  1. The @FunctionalInterface annotation is optional. It's used to ensure that there is only one abstract method.

  2. A functional interface cannot extend another functional interface.

  3. A functional interface can contain any number of Object class methods.

Key Takeaways

After reading this article, you know about functional interfaces, why we need them and how to create them. The Java section on this blog contains other articles you'll find helpful.

Until next time!

🙋🏾‍♀️

Did you find this article valuable?

Support Maddy by becoming a sponsor. Any amount is appreciated!