Java FunctionalInterface Annotation

Introduction

The @FunctionalInterface annotation in Java is used to indicate that an interface is intended to be a functional interface. It helps ensure that the interface contains exactly one abstract method, making it suitable for lambda expressions and method references.

Table of Contents

  1. What is @FunctionalInterface?
  2. Defining Functional Interfaces
  3. Benefits of Using @FunctionalInterface
  4. Examples of @FunctionalInterface
  5. Conclusion

1. What is @FunctionalInterface?

A functional interface in Java is an interface that has exactly one abstract method. It can also contain default and static methods. The @FunctionalInterface annotation is used to declare such interfaces explicitly.

2. Defining Functional Interfaces

To define a functional interface, annotate it with @FunctionalInterface and ensure it has only one abstract method.

Example:

@FunctionalInterface
public interface Greeting {
    void sayHello(String name);
}

3. Benefits of Using @FunctionalInterface

  • Type Safety: Ensures the interface has only one abstract method.
  • Readability: Clearly indicates the purpose of the interface.
  • Compatibility: Works seamlessly with lambda expressions and method references.

4. Examples of @FunctionalInterface

Example 1: Creating a Functional Interface

This example demonstrates how to create a functional interface and use it with a lambda expression.

@FunctionalInterface
interface Calculator {
    int add(int a, int b);
}

public class FunctionalInterfaceExample {
    public static void main(String[] args) {
        Calculator calc = (a, b) -> a + b;
        int result = calc.add(5, 3);
        System.out.println("Result: " + result);
    }
}

Example 2: Using Method References

Here, we use a method reference with a functional interface.

@FunctionalInterface
interface Printer {
    void print(String message);
}

public class MethodReferenceExample {
    public static void main(String[] args) {
        Printer printer = System.out::println;
        printer.print("Hello, World!");
    }
}

Conclusion

The @FunctionalInterface annotation in Java provides a clear way to define functional interfaces, ensuring type safety and enhancing code readability. It is especially useful when working with lambda expressions and method references, making Java programming more expressive and concise.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top