Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Java 8 FAQ: Top Questions

3. What are functional interfaces in Java 8?

A functional interface is an interface that contains only one abstract method. These interfaces are used primarily to enable lambda expressions, which provide a way to implement the method without using a class.

πŸ” Key Concept:

Functional interfaces act as targets for lambda expressions and method references.

πŸ—ΊοΈ Step-by-Step Instructions:

  1. Use the @FunctionalInterface annotation for clarity (optional but recommended).
  2. Ensure the interface has only one abstract method.
  3. Use lambda expressions to implement the method inline.

πŸ“₯ Example Input:

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

πŸ† Lambda Usage:

Greeting greet = name -> System.out.println("Hello " + name);
greet.sayHello("Java");

βœ… Java 8 Solution:

public class FunctionalInterfaceExample {
  public static void main(String[] args) {
    Greeting greet = name -> System.out.println("Hello " + name);
    greet.sayHello("Java");
  }
}

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

πŸ“˜ Detailed Explanation:

  • Only one abstract method: Allows the compiler to infer the lambda body.
  • Built-in examples: Runnable, Callable, Comparator, Predicate, Function.
  • @FunctionalInterface: Annotation to enforce the contract and help documentation.

πŸ› οΈ Use Cases:

  • Event listeners and command patterns.
  • Lambda expression support in APIs.
  • Defining concise single-method logic units.