@FunctionalInterface
- Java course
- Advanced
- Lesson 17/82
- 5 min
Learn marking with @FunctionalInterface.
The @FunctionalInterface annotation
The @FunctionalInterface annotation declares that an interface has a single abstract method (SAM). This lets the compiler prevent a second abstract method from being added by accident.
Example: @FunctionalInterface interface StringOp { String apply(String s); }. Here apply is the single abstract method. If you add another abstract method to the interface the compiler errors out. The annotation is not required; but it is good practice to keep the single-abstract-method rule explicit.
The java.util.function package
Java's java.util.function package contains common functional interfaces. Besides Function, Predicate, Consumer and Supplier, there are specialized versions for primitive types.
For example IntFunction<R> takes an int and returns R; IntPredicate takes an int and returns boolean. These specialized interfaces reduce the boxing overhead. It is good practice to look for an existing one before defining a new interface.
Practice Define and use a custom functional interface
Define a MathOp interface with @FunctionalInterface; it should have an int apply(int a, int b) method. In main, assign an addition lambda (a, b) -> a + b to a MathOp variable. Print the result of apply(3, 4) with System.out.println.
Starter code
// Define the MathOp interface (one abstract method)
// Its apply method takes two ints
// In main, use a lambda to add, print the resultSample solution
@FunctionalInterface
interface MathOp {
int apply(int a, int b);
}
public class CustomFunc {
public static void main(String[] args) {
MathOp add = (a, b) -> a + b;
System.out.println(add.apply(3, 4));
}
}Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the @FunctionalInterface rules
| Term | Meaning |
|---|---|
@FunctionalInterface |
Single abstract method |
Single Abstract Method |
SAM type |
default |
Method with body |
static |
Class method |
2 How many abstract methods can a @FunctionalInterface have at most?
- One Correct answer
- Two
- Unlimited
- Three
Explanation: Exactly one abstract method is required.
3 Complete the annotation
@____
interface MathOp {
int apply(int a, int b);
}
@FunctionalInterface
interface MathOp {
int apply(int a, int b);
}
Explanation: @FunctionalInterface guarantees a single abstract method.