Yes, it is possible to define our own Functional Interfaces. We use Java 8 provides the @FunctionalInterface annotation to mark an interface as a Functional Interface.
We need to follow these rules to define a Functional Interface:
Define an interface with one and only one abstract method.
We cannot define more than one abstract method.
Use @FunctionalInterface annotation in the interface definition.
We can define any number of other methods like default methods, static methods.
The below example illustrates defining our own Functional Interface:
Let's create a Sayable interface annotated with @FunctionalInterface annotation.
@FunctionalInterface
interface Sayable{
void say(String msg); // abstract method
}
Let's demonstrate a custom functional interface via the main() method.
public class FunctionalInterfacesExample {
public static void main(String[] args) {
Sayable sayable = (msg) -> {
System.out.println(msg);
};
sayable.say("Say something ..");
}
}