Java : @FunctionalInterface (annotation) with Examples
FunctionalInterface (Java SE 20 & JDK 20) API Examples.
You will find code examples on most FunctionalInterface methods.
Summary
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
- API Examples