What is a Functional Interface in Java?


Definition

A functional interface in Java must have exactly one abstract method and may have other default or static methods.

Example

  
    @FunctionalInterface
public interface Calculator {
  int add(int a, int b);
  default void log(String message) {
    System.out.println("Log: " + message);
  }
  static void showResult(int result) {
    System.out.println("Result: " + result);
  }
}

// Using Lambda
Calculator calculator = (a, b) -> a + b;
int result = calculator.add(5, 3);
Calculator.showResult(result);

 

A default method in an interface offers a built-in implementation that can be replaced by any class using it. This feature is exclusive to interfaces.

Commentaires

Posts les plus consultés de ce blog

Restoring the Local Changes Tab in IntelliJ IDEA (2024)

Resolving Concurrency Conflicts in Java REST APIs: A Case of 412 Precondition Failed

Circular Dependency Warning in IntelliJ with Maven in a Java Web Project