What is the @FunctionalInterface annotation in Java?

What is a functional interface?

A functional interface is an interface with exactly one abstract method but can have any number of default, static methods. A functional interface can extend another interface only when it does not have any abstract method.

@FunctionalInterface

The @FunctionalInterface annotation is an informative annotation that indicates whether or not an interface type declaration is meant to be a functional interface.

We can create a custom functional interface using the @FunctionalInterface annotation. Lambda expressions, method references, and constructor references can create functional interface instances.

Code

public class Main {
@FunctionalInterface
public interface Talkable {
void talk(String text);
}
public static void main(String[] args){
Talkable talkable = (text -> System.out.println("Talking - " + text));
String textToTalk = "Hello Edpresso";
talkable.talk(textToTalk);
}
}

Explanation

  • Lines 3-6: We define an interface Talkable with only one abstract method, i.e., talk(). We annotate the interface with the @FunctionalInterface annotation. This indicates that it’s a functional interface.
  • Line 10: We define an implementation/instance of the Talkable interface called talkable. This prints the given text to the console.
  • Line 11: We define the text to be printed.
  • Line 12: The talk() method is called with the text defined in line 11.

The code throws an error if we introduce another abstract method to the Talkable interface. The error indicates multiple non-overriding abstract methods in the Talkable interface.

Free Resources