Inheritance and @FunctionalInterface
You'll learn how the single abstract method (SAM) rule applies when a functional interface extends another interface.
Extending Functional Interfaces
When a functional interface extends another interface, Java counts the total number of abstract methods across the entire inheritance chain. The key rule: even with inheritance, there can only be one abstract method in the final interface for it to remain functional.
If the parent interface has an abstract method and the child interface:
- Inherits it without adding new methods → Still functional (1 abstract method total)
- Adds another abstract method → No longer functional (2+ abstract methods)
- Overrides with the same signature → Still functional (still just 1 abstract method)
How It Works
Think of it like a family heirloom: if your parent interface passes down one abstract method, you can keep that single method (functional), but the moment you add a second abstract method, you've broken the "single" rule.
@FunctionalInterface
interface Parent {
void doSomething();
}
// Valid: inherits one abstract method
@FunctionalInterface
interface Child extends Parent {
// No new abstract methods added
}
// INVALID: would cause compiler error
// @FunctionalInterface
// interface BadChild extends Parent {
// void doSomethingElse(); // Second abstract method!
// }
// Valid: override with same signature (still one method)
@FunctionalInterface
interface GoodChild extends Parent {
@Override
void doSomething(); // Just redefining the same contract
}
Remember: default and static methods don't count toward the abstract method total, so you can add those freely in child interfaces.
Key Takeaway: A functional interface can extend another interface, but the complete inheritance hierarchy must contain exactly one abstract method for @FunctionalInterface to compile successfully.