Question
Is it possible for a Java @FunctionalInterface to include default methods?
@FunctionalInterface
public interface MyFunctionalInterface {
void myMethod();
default void myDefaultMethod() {
System.out.println("This is a default method");
}
}
Answer
In Java, a `@FunctionalInterface` can indeed contain default methods. A functional interface is defined as an interface that has exactly one abstract method, which makes it suitable for lambda expressions. Default methods do not count as abstract methods, allowing them to coexist with the single abstract method requirement.
@FunctionalInterface
public interface Greeting {
void sayHello(String name);
default void greet() {
System.out.println("Hello there!");
}
}
public class GreetingDemo {
public static void main(String[] args) {
Greeting greeting = name -> System.out.println("Hello, " + name);
greeting.sayHello("Alice"); // Calls the abstract method
greeting.greet(); // Calls the default method
}
}
Causes
- A functional interface is generally used to represent a single behavior or action using a lambda expression.
- Default methods were introduced in Java 8 to provide a means of adding new methods to interfaces without breaking existing implementations.
Solutions
- To declare a functional interface with default methods, you simply annotate your interface with `@FunctionalInterface` and define one abstract method along with any number of default methods.
- You can implement the interface using a lambda expression for the abstract method.
Common Mistakes
Mistake: Annotating an interface with @FunctionalInterface but including more than one abstract method.
Solution: Ensure that the interface contains exactly one abstract method.
Mistake: Forgetting to use default keyword when defining a default method.
Solution: Always prefix your default method with the keyword 'default'.
Helpers
- @FunctionalInterface
- default methods in Java
- Java functional interface
- Java 8 default methods
- lambdas in Java