Functional Interfaces

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • A Functional Interface is an interface that contains exactly one abstract method.
  • It can have any number of default or static methods.
  • It is the foundation for Lambda Expressions and Method References in Java.
  • You can annotate it with @FunctionalInterface to let the compiler enforce the single abstract method rule.

Concept

Java is strictly Object-Oriented, meaning everything must belong to a class or an object. You cannot just pass a raw function around like you can in JavaScript.

To introduce functional programming (Lambdas) in Java 8, the designers used Functional Interfaces. When you write a Lambda Expression, the compiler looks at the context and automatically converts your lambda into an instance of a Functional Interface. The lambda’s body becomes the implementation of the interface’s single abstract method.

Examples

// The annotation is optional but highly recommended.
// It causes a compiler error if you accidentally add a second abstract method.
@FunctionalInterface
interface StringProcessor {
    
    // Exactly ONE abstract method
    String process(String str); 
    
    // Can have multiple default methods
    default void printLength(String str) {
        System.out.println(str.length());
    }
    
    // Can have static methods
    static void hello() {
        System.out.println("Hello");
    }
}

public class FunctionalInterfaceExample {
    public static void main(String[] args) {
        
        // The lambda expression provides the implementation for the 'process' method
        StringProcessor toUpperCaseProcessor = str -> str.toUpperCase();
        
        String result = toUpperCaseProcessor.process("hello world");
        System.out.println(result); // HELLO WORLD
    }
}

Interview Questions

Q: If an interface extends another interface, can it still be a Functional Interface?
A: Yes, but only if the combined total of abstract methods remains exactly one. If Interface A has one abstract method, and Interface B extends A and adds NO new abstract methods, Interface B is a Functional Interface. If Interface B adds a new abstract method, it is no longer functional.

Q: Why are default and static methods allowed in Functional Interfaces?
A: The “Functional” requirement only cares about the single abstract method, because that is the method the Lambda expression will implement. default and static methods already have an implementation provided by the interface itself, so they don’t interfere with the compiler’s ability to map a lambda to the abstract method.