0Pricing
Java Academy · Lesson

Custom Functional Interfaces

Define your own with @FunctionalInterface.

What Makes an Interface Functional

A functional interface has exactly one abstract method (SAM). That single method is what a lambda implements.

  • Default and static methods do not count against the limit.
interface Greeter {
    String greet(String name);
}

public class Main {
    public static void main(String[] args) {
        Greeter g = name -> "Hello, " + name;
        System.out.println(g.greet("Ada"));
    }
}

The @FunctionalInterface Annotation

@FunctionalInterface tells the compiler to enforce the single-abstract-method rule. If you accidentally add a second abstract method, compilation fails.

@FunctionalInterface
interface Calculator {
    int compute(int a, int b);
}

public class Main {
    public static void main(String[] args) {
        Calculator add = (a, b) -> a + b;
        System.out.println(add.compute(3, 4));
    }
}

All lessons in this course

  1. Function and BiFunction
  2. Supplier and Consumer
  3. Predicate and Composition
  4. Custom Functional Interfaces
← Back to Java Academy