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:
- Use the
@FunctionalInterface
annotation for clarity (optional but recommended). - Ensure the interface has only one abstract method.
- 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.