liveBook · Manning

Functional interface

As explained in The Art of Code

A functional interface is a Java interface with one abstract method that can serve as the target type for a lambda expression or method reference.

A functional interface defines exactly one unimplemented, implicitly abstract method. That single method gives Java enough information to accept a lambda as the interface’s behavior, replacing a small implementation class with a concise expression. section 6.2

From implementation class to behavior

A verbose version packages the predicate in a class: `LengthGreaterThanThree implements StringPredicate` and returns `value.length() > 3` from `test`. The same intent can be supplied directly as a lambda: `StringPredicate test = value -> value.length() > 3;`. The interface describes the input and output contract; the lambda supplies the transformation. section 6.2

@FunctionalInterface
public interface StringPredicate {
  boolean test(String value);
}

Inspect the minimal interface declaration that makes the lambda target type possible. section 6.2

Use functional interfaces with these practical distinctions:

  • Add `@FunctionalInterface` when defining a custom interface; the annotation is optional but makes accidental second abstract methods compile-time errors. section 6.2
  • Prefer Java’s `Predicate`, `Function`, `Consumer`, or `Supplier` when an existing signature matches instead of creating a custom interface. section 6.2
  • Use lambdas and method references to pass behavior as data, especially when a pipeline can state the intended transformation more clearly than explicit iteration. section 6.5

How The Art of Code covers it

How deep it goes
Defines the single-abstract-method rule, optional compiler enforcement, and standard alternatives, but stops short of broader interface mechanics.
Examples
Uses StringPredicate, LengthGreaterThanThree, Predicate, and a stream filtering words longer than three characters.
What it assumes
Assumes Java interface and method basics while teaching the single-abstract-method contract through input and output signatures.
What you can do after
Apply Java lambdas to replace trivial implementation classes and express reusable transformations with matching functional-interface signatures.
How it connects
Connects functional interfaces with lambda expressions, method references, pure functions, the Stream API, and declarative pipelines.

Also explained in

Compare how 3 books explain functional interface →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Art of Code. The section links point to the parts of the book it draws on.