Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
annotation
communitycreator

What is the @FunctionalInterface annotation in Java?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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);
}
}
FunctionalInterface

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.

RELATED TAGS

java
annotation
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring