skip to content

Why can Runnable and Comparator, both older than Java 8, be lambda targets when an abstract class with one abstract method cannot?

level: middleimportance: should knowfreq 52%

answer

  1. target type comes from context
  2. a structural test with no opt-in
  3. the definition's first requirement
  4. Object's public methods skip the count
  5. a lambda's this is the enclosing one

basics

~20 s

A lambda's target must be a functional interface, a shape test: one abstract method beyond Object's public ones, no opt-in. Runnable and Comparator already had that shape. An abstract class is not an interface, so it never qualifies.

solid answer

~50 s

JLS 15.27.3 makes a lambda compatible only with a functional interface type, and JLS 9.8 defines that by structure: an interface, not sealed, with one abstract method apart from `Object`'s public methods. No opt-in is involved, so `Runnable` with `run` and `Comparator` with `compare` (its re-declared `equals` does not count) qualified as soon as Java 8 arrived. Java 8 did annotate both with `@FunctionalInterface` and gave `Comparator` default and static methods, but eligibility rests on neither. An abstract class fails the first requirement, even with one abstract method and no fields. That fits how lambdas work: a lambda's `this` is the enclosing context's, and evaluating one may reuse an existing object, so a class's constructors and instance state have no place. For a class, write an anonymous subclass or a factory that takes a lambda, as `ThreadLocal.withInitial` does.

code

java · 23 lines
java
abstract class Task {
    abstract void run();

    // Task t = () -> {};  // error: incompatible types: Task is not a functional interface

    static Task of(Runnable body) {
        return new Task() {
            @Override
            void run() {
                body.run();
            }
        };
    }
}

class Demo {
    public static void main(String[] args) {
        Runnable plain = () -> System.out.println("target is an interface");
        Task wrapped = Task.of(() -> System.out.println("lambda reaches the class through a factory"));
        plain.run();
        wrapped.run();
    }
}

go deeper

for a junior

Recall that a lambda needs a functional interface as its target: an interface with one abstract method. Runnable and Comparator qualify, and an abstract class never does, however small it is.

for a middle

Explain the two JLS clauses: the target must be a functional interface type, and that type is defined by its members, not an opt-in. Show why Comparator's equals and its default methods stay out of the count.

for a senior

Show the design consequence: a class-based extension point cannot take lambdas, so offer a factory such as ThreadLocal.withInitial or extract an interface. Know javac's message and the metafactory's separate run-time check.

for a principal

Weigh abstract class against interface for a public callback type: a class keeps shared state and constructors but gives up lambda syntax and takes the caller's only superclass slot. Decide early, because switching later breaks existing subclasses.

## The rule, in two clauses A **lambda expression** has no type of its own. It takes a **target type** from its context: an assignment, a method argument or a cast. Two clauses of the Java Language Specification (JLS) decide what that target may be: - **JLS 15.27.3**: a lambda is compatible with a target type `T` "if T is a functional interface type" and the lambda is congruent with that type's function type. - **JLS 9.8**: a **functional interface** is "an interface that is not declared sealed and has just one abstract method (aside from the methods of Object)". That definition is **structural**: it reads the interface's members and asks for no keyword or marker. The `java.lang.FunctionalInterface` Javadoc says so directly: the compiler treats any interface meeting the definition as functional "regardless of whether or not" the annotation is present. ## Why the old interfaces qualified as they stood `Runnable` dates from Java 1.0 and `Comparator` from 1.2, and lambdas arrived in Java 8. Both already had the required shape: | Type | Since | Abstract methods it declares | Counted by JLS 9.8 | |---|---|---|---| | `java.lang.Runnable` | 1.0 | `run` | `run` | | `java.util.Comparator` | 1.2 | `compare`, `equals` | `compare` | `Comparator`'s `equals` has the same signature as a public method of `Object`, so the count skips it, and JLS 9.8 gives `Comparator` as its example for that exclusion. Everything else on it has a body, so it is not abstract: 9 default and 9 static methods at Java 27, and 7 default and 9 static at Java 25, because `max` and `min` arrived in Java 26. Java 8 did touch both types. It annotated them with `@FunctionalInterface`, and it gave `Comparator` its first default and static methods. Neither step is what made them eligible: - The annotation states intent and asks the compiler to verify the definition; it grants nothing. - Adding methods with bodies leaves the abstract count where it was. - An interface declaring only `int twice(int x)`, with no annotation, whose class file has major version 48 (Java 8 writes 52), still takes `x -> x * 2` when compiled and run on Java 27. So a library interface that meets the definition and whose method is not generic, compiled long before lambdas existed, accepts a lambda without being rebuilt. ## Why an abstract class is out The direct answer is the definition's first requirement: a class is not an interface. How few abstract methods it has makes no difference, and neither does having no fields or an `implements Runnable` clause. Given `abstract class Task { abstract void run(); }`: - `Task t = () -> {};` fails with `incompatible types: Task is not a functional interface`. - A cast, `(Task) () -> {}`, fails with the same message. - `@FunctionalInterface` on the class fails too: `Unexpected @FunctionalInterface annotation`. The rule is stated in the JLS. The reasons below are inferred from its other lambda rules, not a rationale quoted from it, and each describes something a class brings that a lambda has no place for: - **Construction.** Creating a class instance runs a constructor, a superclass constructor and instance initializers (JLS 12.5). JLS 15.27.4 lets a lambda's evaluation refer to an existing instance rather than allocate one, which would skip whatever a constructor promised to do per object. - **State.** JLS 15.27.2 says `this` and `super` in a lambda body mean what they mean in the surrounding context. A lambda body could not reach the abstract class's fields or helper methods through `this`, which an anonymous subclass can. - **The object's class.** JLS 15.27.4 specifies the lambda's class as one that "implements the targeted functional interface type", plus any other interface in an intersection target. That model is written in terms of interfaces, with no slot for a target superclass. The run-time linkage agrees. javac compiles a lambda to an `invokedynamic` call site bootstrapped by `java.lang.invoke.LambdaMetafactory`, whose Javadoc describes implementing "one or more interfaces" and calls this the "recommended mechanism" for evaluating lambdas. Its public contract specifies `LambdaConversionException` "if the return type of factoryType is not an interface". That is a Java SE API rule rather than a JLS one; only the message, `... is not an interface`, is implementation detail, from the package-private `AbstractValidatingLambdaMetafactory`. ## What to write instead - **An anonymous subclass** when you need the class's state or constructor: `new Task() { @Override void run() { ... } }`. - **A static factory that takes a functional interface** when callers should keep lambda syntax. The JDK does this: `ThreadLocal` is a concrete class with an overridable `initialValue()`, and `ThreadLocal.withInitial(Supplier)` returns an instance of its package-private subclass `SuppliedThreadLocal`. - **An interface of its own** when the class holds no state worth keeping. Moving a published type from abstract class to interface breaks its existing subclasses, so this choice is cheapest before release. ## Shape alone is not quite enough An interface with one abstract method can still miss: - JLS 9.8 excludes any interface declared `sealed`, a feature final since Java 17 after previews in 15 and 16, and javac reports the same `is not a functional interface` error for one. - If that method is `boolean equals(Object)`, it matches `Object` and leaves nothing to count, so javac reports `no abstract method found`. - If that method is generic, the interface is functional but a lambda still cannot implement it, because JLS 15.27.3 requires a function type with no type parameters. A method reference or a class can. An interface with two unrelated abstract methods fails as well, with `multiple non-overriding abstract methods found`. How that count works through inheritance and generics is a topic of its own.

  • If a Java class must stay abstract, how do you still give its callers lambda syntax?
    Add a static factory that takes a functional interface and returns a subclass wrapping it. The JDK does this with a concrete class: `ThreadLocal` has an overridable `initialValue()`, and `ThreadLocal.withInitial(Supplier)` returns its package-private subclass `SuppliedThreadLocal`, so callers write `ThreadLocal.withInitial(() -> new ArrayList<>())`.
  • Does a single-method interface from a library compiled before Java 8 need recompiling to take a lambda?
    No. JLS 9.8 reads the interface's members, not its class-file version or annotations. An interface declaring only `int twice(int x)`, with no `@FunctionalInterface`, whose class file has major version 48, compiles and runs as a lambda target on Java 27. Only the code containing the lambda must be compiled at Java 8 or later.
  • Is the ban on abstract-class lambda targets enforced only by javac, or also at run time?
    Both. javac rejects the source under JLS 15.27.3. Separately, `LambdaMetafactory.metafactory` specifies `LambdaConversionException` if the return type of `factoryType` is not an interface. That is a Java SE API rule, not a JLS one; only the message, `... is not an interface`, comes from the package-private `AbstractValidatingLambdaMetafactory`. A class file compiled against an interface later replaced by an abstract class reaches it at linkage, as a `BootstrapMethodError`.
  • Why is a sealed Java interface with one abstract method not a lambda target?
    JLS 9.8 excludes any interface declared `sealed`, so javac reports `is not a functional interface`. The exclusion fits what sealing means: the interface's direct subtypes are a closed list, and a lambda's class would be an implementation outside it. Implement the interface in a permitted class instead.

  • Runnable and Comparator had to gain @FunctionalInterface before lambdas could target them.
  • Comparator cannot be functional because it declares both compare and equals as abstract.
  • Lambdas are just anonymous classes, so any class with one abstract method should work.
  • Annotating an abstract class with @FunctionalInterface makes it a valid lambda target.
  • An abstract class is rejected only when it has fields or a constructor with arguments.
  • Old library interfaces must be recompiled with Java 8 before they accept lambdas.

Lambda expressions and functional interface types
Java 1.8
@FunctionalInterface annotation
Java 1.8
java.lang.Runnable
Java 1.0
java.util.Comparator
Java 1.2
Sealed interfaces, which JLS 9.8 excludes
Java 17pre-release 15

Assumes Java 27; lambdas and @FunctionalInterface date from Java 8, sealed interfaces from Java 17 after previews in 15 and 16, and Comparator's default-method count differs at Java 25 without changing the rule.

context