Sub topic 2
Functional Interfaces: One Abstract Method
In the last chapter, you passed behavior to sort with an anonymous class. Java 8 lets you write that same behavior as a short lambda. A lambda can't stand on its own, though. It needs a special kind of interface to give it a type. That kind of interface is called a functional interface, and this chapter covers what it is, how to spot one, and why lambdas depend on it.
What Is a Functional Interface?
An abstract method is a method with a name, parameters, and a return type, but no body. Every method in a plain interface is abstract unless it says otherwise.
A functional interface is an interface that has exactly one abstract method. The rule really is that short. The single method is often called the SAM, short for "single abstract method."
Here is one:
interface Greeter {
String greet(String name);
}Greeter has one abstract method, greet, so it is a functional interface. You don't need any special keyword to make it one. Having one abstract method is enough.
Why a Lambda Needs One
A lambda is a short block of code that you can store in a variable or pass to a method. It has parameters and a body, but no name. A lambda also doesn't say which method it implements.
The functional interface supplies the missing information. Its single abstract method tells Java:
- how many parameters the lambda takes,
- what types those parameters have,
- what type the lambda must return.
When you write a lambda, Java turns it into an object that implements the interface. The lambda's body becomes the body of the one abstract method. With two abstract methods, Java couldn't tell which one the lambda was meant to fill in, so the rule allows only one.
The type that a lambda must match is called its target type. For a lambda, the target type must always be a functional interface.
The program below implements Greeter in three ways. All three produce an object of type Greeter.
interface Greeter {
String greet(String name);
}
public class GreeterDemo {
// Way 1: a normal class that implements the interface
static class PoliteGreeter implements Greeter {
@Override
public String greet(String name) {
return "Good day, " + name;
}
}
public static void main(String[] args) {
Greeter g1 = new PoliteGreeter();
// Way 2: an anonymous class
Greeter g2 = new Greeter() {
@Override
public String greet(String name) {
return "Hi, " + name;
}
};
// Way 3: a lambda (allowed because Greeter has one abstract method)
Greeter g3 = name -> "Hey, " + name;
System.out.println(g1.greet("Ada")); // Good day, Ada
System.out.println(g2.greet("Ada")); // Hi, Ada
System.out.println(g3.greet("Ada")); // Hey, Ada
}
}Save this as GreeterDemo.java, then run javac GreeterDemo.java and java GreeterDemo.
The lambda name -> "Hey, " + name has no type written anywhere inside it. Java reads the type from the left side, Greeter g3. Because greet takes a String and returns a String, Java knows name is a String and the result must be a String. The next chapter covers lambda syntax in detail.
What Does Not Count Toward the One
Real interfaces often contain more than one method. They can still be functional, because some kinds of methods are left out of the count.
Default methods
A default method is an interface method that has a body. It starts with the keyword default. Because it already has a body, it is not abstract, so it doesn't count.
Static methods
A static method belongs to the interface itself, not to an object, and it has a body. It doesn't count either.
interface Shape {
double area(); // the one abstract method
default String describe() { // has a body: not counted
return "Area: " + area();
}
static Shape unitSquare() { // static: not counted
return () -> 1.0;
}
}
public class ShapeDemo {
public static void main(String[] args) {
Shape circle = () -> Math.PI * 2 * 2; // circle with radius 2
System.out.println(circle.describe()); // Area: 12.566370614359172
System.out.println(Shape.unitSquare().describe()); // Area: 1.0
}
}Shape has three methods but only one abstract method, so it is functional. The lambda supplies area, and describe can still be called on the result.
Methods that copy ones from Object
Every Java class already gets methods such as equals, hashCode, and toString from the Object class. Sometimes an interface lists one of these as an abstract method, mostly so it can be documented. That method doesn't count, since every object already has it.
java.util.Comparator is the best-known example. Its source declares two abstract methods:
int compare(T o1, T o2);
boolean equals(Object obj);equals comes from Object, so it is ignored. compare is the only one that counts, and Comparator is a functional interface. That's why you could write (a, b) -> a.compareToIgnoreCase(b) in the last chapter.
Inherited Methods Do Count
An interface can extend another interface. Abstract methods it inherits from the parent count toward the total.
interface Named {
String name();
}
// Adds nothing, so it still has one abstract method: functional
interface Labeled extends Named {
}
// Inherits name() and adds tag(): two abstract methods, not functional
interface Tagged extends Named {
String tag();
}
public class InheritDemo {
public static void main(String[] args) {
Labeled label = () -> "box";
System.out.println(label.name()); // box
// Tagged t = () -> "box"; // does not compile: Tagged has two abstract methods
}
}Labeled has no methods written inside it, but it inherits name(), so it is functional.
When the Rule Is Broken
Here is an interface with two abstract methods:
interface Converter {
String toText(int n);
int fromText(String s);
}
public class ConverterDemo {
public static void main(String[] args) {
// A full class or anonymous class still works:
Converter c = new Converter() {
@Override
public String toText(int n) { return String.valueOf(n); }
@Override
public int fromText(String s) { return Integer.parseInt(s); }
};
System.out.println(c.toText(7) + "!"); // 7!
System.out.println(c.fromText("8") + 1); // 9
// A lambda does not:
// Converter bad = n -> String.valueOf(n);
}
}If you remove the // from the last line, javac reports an error like this:
error: incompatible types: Converter is not a functional interface
multiple non-overriding abstract methods found in interface ConverterConverter is still a valid interface, and classes can still implement it. The only thing you lose is the ability to write it as a lambda.
An empty interface, with no abstract methods at all, is not functional either. A lambda would have no method to fill in.
Functional Interfaces You Already Know
The Java library had functional interfaces long before lambdas existed. They just weren't called that yet. Because they each have one abstract method, all of them accept lambdas today.
| Interface | Package | Single abstract method | Typical use |
|---|---|---|---|
| `Runnable` | `java.lang` | `void run()` | Code to run, often on a thread |
| `Comparator<T>` | `java.util` | `int compare(T a, T b)` | Ordering for sorting |
| `Callable<V>` | `java.util.concurrent` | `V call()` | A task that returns a result |
| `ActionListener` | `java.awt.event` | `void actionPerformed(ActionEvent e)` | Reacting to a button click |
Here are two of them used with lambdas:
import java.util.concurrent.Callable;
public class OldInterfaces {
public static void main(String[] args) throws Exception {
Runnable hello = () -> System.out.println("Running!");
hello.run(); // Running!
Callable<Integer> answer = () -> 42;
System.out.println(answer.call()); // 42
}
}Java 8 also added a whole package of general-purpose functional interfaces, java.util.function. A later chapter covers it.
Checklist: Is This Interface Functional?
Count only the abstract methods that remain after you leave out the ones Java ignores.
Exercises
Exercise
Is this interface functional? interface Printer { void print(String s); default void printTwice(String s) { print(s); print(s); } }
Show answer
Yes. print is the only abstract method. printTwice is a default method with a body, so it does not count.
Exercise
An interface declares two abstract methods: int score(String s) and String toString(). Can you assign a lambda to it? Why?
Show answer
Yes. toString() matches a public method of Object, which every object already has, so it is not counted. Only score remains, so the interface is functional.
Exercise
interface Base { void start(); } and interface Child extends Base { void stop(); }. Which of the two accepts a lambda?
Show answer
Only Base. Child inherits start() and adds stop(), so it has two abstract methods and is not functional.
Exercise
Write a functional interface named Checker whose method takes an int and returns a boolean. Then assign a lambda that returns true when the number is greater than 10 and print the result for 15.
Show answer
interface Checker { boolean check(int n); } then, inside main: Checker big = n -> n > 10; System.out.println(big.check(15)); which prints true.