Sub topic 8
Defining Your Own Functional Interfaces
The java.util.function package covers most everyday needs. Function, Predicate, Consumer, and Supplier handle a large share of the work. Sometimes none of them fits well, and then you can write your own functional interface. This chapter shows how to do that, how the @FunctionalInterface annotation protects you, and how to decide between a custom interface and a built-in one.
A Quick Reminder
A functional interface is an interface with exactly one abstract method. An abstract method is a method that has a name and parameters but no body. A lambda supplies that missing body.
Any interface that follows this rule can be the target of a lambda. You do not need special permission from Java to make one. If you write an interface with one abstract method, you have written a functional interface.
Your First Custom Functional Interface
Here is a small interface for math operations on two whole numbers:
@FunctionalInterface
interface Calculator {
int apply(int a, int b);
}
public class CalculatorDemo {
public static void main(String[] args) {
Calculator add = (a, b) -> a + b; // expression body
Calculator multiply = (int a, int b) -> { // explicit types, block body
return a * b;
};
System.out.println(add.apply(2, 3)); // 5
System.out.println(multiply.apply(2, 3)); // 6
}
}Save this as CalculatorDemo.java, then compile and run it:
javac CalculatorDemo.java
java CalculatorDemoHere is how it works:
Calculatorhas one abstract method,apply. It takes twointvalues and returns anint.- The lambda
(a, b) -> a + bmatches that shape. The compiler knowsaandbareintbecauseCalculatorsays so. - Calling
add.apply(2, 3)runs the lambda's body.
The name of the method does not matter to the lambda. You could call it compute or run. The lambda only has to match the parameter types and the return type.
What @FunctionalInterface Does
@FunctionalInterface is an annotation. An annotation is a label that starts with @ and gives extra information to the compiler or to tools.
This annotation tells the compiler: "I mean this to be a functional interface. Please check it." If the interface does not have exactly one abstract method, the compiler stops with an error.
The annotation is optional. Without it, Calculator would still work with lambdas. So why use it? It protects your code later. Suppose a teammate adds a second abstract method months from now. Without the annotation, the interface compiles fine, and every lambda that uses it breaks, possibly in files far away. With the annotation, the error shows up right on the interface, where the mistake was made.
@FunctionalInterface
interface Shape {
double area();
// Uncommenting the next line causes a compile error on this interface:
// "multiple non-overriding abstract methods found in interface Shape".
// double perimeter();
}
public class ShapeDemo {
public static void main(String[] args) {
Shape unitSquare = () -> 1.0;
System.out.println(unitSquare.area()); // 1.0
}
}What Counts as "One Abstract Method"
The rule is "exactly one abstract method", but some methods do not count toward the total. The table lists what you may add without breaking the rule.
| Member in the interface | Counts toward the one? | Why |
|---|---|---|
| A method with no body, like `int apply(int a, int b);` | Yes | It is abstract. The lambda fills it in. |
| A `default` method with a body | No | It already has code. |
| A `static` method with a body | No | It belongs to the interface itself, not to the object. |
| A method that matches one from `Object`, like `boolean equals(Object o);` | No | Every object already has it from `Object`. |
| A constant, like `int LIMIT = 10;` | No | It is a field, not a method. |
Default and Static Methods
A default method is an interface method with a body, marked with the word default. Every object of that interface type gets it for free. A static method in an interface is a helper you call on the interface name itself.
Both are useful in custom functional interfaces. A default method can build on the single abstract method. A static method can hand out ready-made instances.
import java.util.Arrays;
import java.util.List;
@FunctionalInterface
interface Greeter {
String greet(String name); // the one abstract method
default void greetAll(List<String> names) {
for (String n : names) {
System.out.println(greet(n));
}
}
static Greeter polite() {
return name -> "Good day, " + name + ".";
}
}
public class GreeterDemo {
public static void main(String[] args) {
Greeter casual = name -> "Hey " + name + "!";
casual.greetAll(Arrays.asList("Ada", "Linus"));
// Hey Ada!
// Hey Linus!
Greeter formal = Greeter.polite();
System.out.println(formal.greet("Grace")); // Good day, Grace.
}
}The lambda supplies only greet. The method greetAll comes along for free, and it calls whatever greet the lambda provided. The built-in interfaces work the same way, which is how Function gets its andThen method. The next chapter covers that.
Methods from Object
Sometimes you will see an interface that lists equals or toString and still counts as functional. java.util.Comparator is a real example: it declares equals but is still a functional interface.
@FunctionalInterface
interface Rule {
boolean check(String input);
boolean equals(Object other); // matches Object.equals, does not count
String toString(); // matches Object.toString, does not count
}
public class RuleDemo {
public static void main(String[] args) {
Rule notBlank = s -> !s.trim().isEmpty();
System.out.println(notBlank.check(" ")); // false
System.out.println(notBlank.check("hi")); // true
}
}The compiler accepts this because every object already has equals and toString from Object. The lambda only needs to supply check.
Generic Custom Interfaces
A generic interface uses type parameters, like the T in List<T>, so one interface can work with many types. The standard library has Function<T, R> for one input and BiFunction<T, U, R> for two. It has nothing for three inputs. You can write that yourself:
@FunctionalInterface
interface TriFunction<A, B, C, R> {
R apply(A a, B b, C c);
}
public class TriFunctionDemo {
public static void main(String[] args) {
TriFunction<String, Integer, Integer, String> slice =
(s, start, end) -> s.substring(start, end);
TriFunction<Integer, Integer, Integer, Integer> sum3 =
(x, y, z) -> x + y + z;
System.out.println(slice.apply("lambda", 1, 4)); // amb
System.out.println(sum3.apply(1, 2, 3)); // 6
}
}The same TriFunction works for strings, numbers, or any other types you choose. The compiler fills in A, B, C, and R from the types you write in the angle brackets.
Built-in or Custom? How to Choose
Use a built-in interface when one fits. Other Java developers already know Predicate<String>, and the built-ins come with helper methods such as and and andThen. A custom interface makes sense in a few specific cases.
| Situation | Better choice | Example |
|---|---|---|
| One input, one output | Built-in `Function<T, R>` | Turn a `String` into its length |
| A yes/no test | Built-in `Predicate<T>` | Is this number even? |
| Three or more inputs | Custom | `TriFunction<A, B, C, R>` |
| The name should explain your domain | Custom | `PriceRule`, `Validator`, `Shape` |
| The method must throw a checked exception | Custom | A method declared with `throws IOException` |
| You want extra default methods tied to your problem | Custom | `Greeter.greetAll` |
Common Mistakes
- Two abstract methods. The interface compiles without the annotation, but no lambda can target it. Add
@FunctionalInterfaceto catch this early. - Forgetting the body on a helper. If you write
void log(String s);meaning it as a helper, it becomes a second abstract method. Helpers needdefaultorstaticand a body. - Reinventing a built-in. Writing
interface StringTester { boolean test(String s); }duplicatesPredicate<String>and loses its helper methods. Prefer the built-in unless the name adds real meaning. - Mismatched shape. A lambda
(a, b) -> a + bcannot targetShape, becausearea()takes no parameters. The lambda's parameter count must match the abstract method's parameter count.
Exercise
Will this interface compile with the annotation? Explain why or why not. @FunctionalInterface interface Formatter { String format(String s); default String formatTwice(String s) { return format(format(s)); } String toString(); }
Show answer
Yes. It has only one abstract method that counts, format. formatTwice is a default method with a body, so it does not count. toString matches a method from Object, so it does not count either.
Exercise
Write a functional interface named Discount with a method double apply(double price). Then create a lambda that takes 10% off and print the result for a price of 50.0.
Show answer
@FunctionalInterface interface Discount { double apply(double price); } and in main: Discount tenOff = price -> price * 0.9; System.out.println(tenOff.apply(50.0)); This prints 45.0.
Exercise
You need a lambda that takes a String and returns a boolean. No checked exceptions are involved, and the code is general-purpose. Should you write a custom interface? Why?
Show answer
No. Use the built-in Predicate<String>. Other developers already know it, and it comes with helper methods like and, or, and negate. A custom interface would add a new type without adding meaning.