Java : @FunctionalInterface (annotation) with Examples

FunctionalInterface (Java SE 20 & JDK 20) API Examples.
You will find code examples on most FunctionalInterface methods.


Summary

An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification. Conceptually, a functional interface has exactly one abstract method.

Class diagram

Instances of functional interfaces can be created with lambda expressions.

@FunctionalInterface
public interface Foo {
    void func();
}
public class Main {
    public static void main(String[] args) {
        // A lambda expression.
        final Foo foo = () -> System.out.println("Foo!");
        foo.func();
    }
}

// --- PowerShell ---
//PS R:\java-work> ls -Name
//Foo.java
//Main.java
//
//PS R:\java-work> javac *.java
//
//PS R:\java-work> java Main
//Foo!

An example of a compile error :

@FunctionalInterface
public interface Foo {
    void func1();

    void func2();
}

// --- PowerShell ---
//PS R:\java-work> javac *.java
//Foo.java:2: error: Unexpected @FunctionalInterface annotation
//@FunctionalInterface
//^
//  Foo is not a functional interface
//    multiple non-overriding abstract methods found in interface Foo
//1 error

Please see also Java Language Specification :


Related posts

To top of page