Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Functional Interfaces in Java

1. Introduction

Functional Interfaces are a core concept in Java's functional programming capabilities introduced in Java 8. They allow the use of lambda expressions, which enable clearer and more concise code.

2. Definition

A Functional Interface is an interface that contains exactly one abstract method. These interfaces can have multiple default or static methods but can only have one abstract method to qualify as a functional interface.

Important Note: Common functional interfaces in Java include Runnable, Callable, Comparator, and interfaces from the java.util.function package such as Function, Consumer, and Supplier.

3. Key Concepts

  • Functional Interfaces can be used as the assignment target for lambda expressions or method references.
  • You can use the @FunctionalInterface annotation to indicate that an interface is intended to be a functional interface. This is optional but helps with code clarity.
  • Lambda expressions provide a clear and concise way to represent a single method interface using an expression.

4. Code Examples

4.1 Basic Example of a Functional Interface


@FunctionalInterface
interface MyFunctionalInterface {
    void execute();
}

public class Main {
    public static void main(String[] args) {
        MyFunctionalInterface myFunc = () -> System.out.println("Hello, Functional Interface!");
        myFunc.execute();
    }
}
        

4.2 Using Built-in Functional Interfaces


import java.util.function.Function;

public class Main {
    public static void main(String[] args) {
        Function square = x -> x * x;
        System.out.println("Square of 5: " + square.apply(5)); // Outputs 25
    }
}
        

5. Best Practices

  1. Always use the @FunctionalInterface annotation for clarity.
  2. Keep functional interfaces simple; ideally, they should represent a single action.
  3. Utilize built-in functional interfaces from the java.util.function package whenever possible.

6. FAQ

What is a lambda expression?

A lambda expression is a concise way to represent an anonymous function that can be passed around. It can be used primarily to implement functional interfaces.

Can a functional interface have multiple abstract methods?

No, a functional interface cannot have multiple abstract methods. It should have exactly one abstract method to maintain its functional nature.

What happens if I annotate an interface with @FunctionalInterface that is not a functional interface?

The compiler will throw an error indicating that the interface does not satisfy the requirements of a functional interface.