How to use @FunctionalInterface annotation in Java 8

Tags: FunctionalInterface Java 8

The @FunctionalInterface annotation is type of information annotation which introduce from Java 8 to indicate that an interface is intended to be a functional interface. In this Java 8 tutorial we learn how to use the @FunctionalInterface annotation in Java programs.

How to use @FunctionalInterface annotation in Java 8

In the following Java example program, we have the Calculator interface is intended to be a function interface which is an interface contains only one abstract method. In this case we can use the @FunctionalInteface annotation for Calculator interface declaration.

Calculator.java

@FunctionalInterface
public interface Calculator {
    int calculate(int value);
}

FunctionalInterfaceExample.java

public class FunctionalInterfaceExample {
    public static void main(String... args) {
        Calculator calculateSquare = (int value) -> value * value;
        Calculator calculateDouble = (int value) -> value * 2;
        Calculator calculateTriple = (int value) -> value * 3;

        int value = 4;
        int squareValue = calculateSquare.calculate(value);
        int doubleValue = calculateDouble.calculate(value);
        int tripleValue = calculateTriple.calculate(value);

        System.out.println("Square of " + value + " is " + squareValue);
        System.out.println("Double of " + value + " is " + doubleValue);
        System.out.println("Triple of " + value + " is " + tripleValue);
    }
}
The output is.
Square of 4 is 16
Double of 4 is 8
Triple of 4 is 12

Is @FunctionalInterface a mandatory annotation for functional interface?

It is not mandatory to define functional interface with @FunctionalInterface annotation.

But it is the good practice to use it with the interfaces that we intend to be a functional interface.

Unexpected @FunctionalInterface annotation Compile Error

If we add more than one method to an interface annotated with @FunctionalInterface annotation then it throws the compile error. It help developer to avoid adding more method that the code does not expected. For example we add one more method to the Calculator interface as below.

@FunctionalInterface
public interface Calculator {
    int calculate(int value);
    int execute(int value);
}
The compile error.
error: Unexpected @FunctionalInterface annotation
@FunctionalInterface
^
  Calculator is not a functional interface
    multiple non-overriding abstract methods found in interface Calculator

Happy Coding 😊