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 {@FunctionalInterfacepublic 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
Talkablewith only one abstract method, i.e.,talk(). We annotate the interface with the@FunctionalInterfaceannotation. This indicates that it’s a functional interface. - Line 10: We define an implementation/instance of the
Talkableinterface calledtalkable. 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.