Java 8 - What are functional interfaces?

We will start with What Functional interfaces are and then write example code.

1. What are functional interfaces?

Java 8 reincarnated SAM interfaces and termed them Functional interfaces. Functional interfaces have single abstract method and are eligible to be represented with Lambda expression. @FunctionalInterface annotation is introduced in Java 8 to mark an interface as functional. It ensures at compile-time that it has only single abstract method, otherwise it will throw compilation error.

1.1. Defining functional interface

We use @FunctionalInterface annotation to mark interface as functional interface.

@FunctionalInterface
public interface Spec<T> {
boolean isSatisfiedBy(T t);
}

Functional interfaces can have default and static methods in them and still remains functional interface.

@FunctionalInterface
public interface Spec<T> {
boolean isSatisfiedBy(T t);

default Spec<T> not() {
return (t) -> !isSatisfiedBy(t);
}

default Spec<T> and(Spec<T> other) {
return (t) -> isSatisfiedBy(t) && other.isSatisfiedBy(t);
}

default Spec<T> or(Spec<T> other) {
return (t) -> isSatisfiedBy(t) || other.isSatisfiedBy(t);
}
}

If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere.



Tags: java.util.function package, Functional Interfaces, Java 8 @FunctionalInterface annotation, Java, Java 8

← Back home