Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 08:07:10 Viewed : 236
The @FunctionalInterface
annotation is a feature introduced in Java 8 to provide a clear and explicit way to declare that an interface is intended to be a functional interface. A functional interface is an interface that has exactly one abstract method, and it can optionally contain multiple default or static methods. Functional interfaces are a key concept in Java is support for functional programming.
Here are some key points about the @FunctionalInterface
annotation:
Purpose:
@FunctionalInterface
annotation is to express the intent of an interface to be a functional interface.Compile-Time Checks:
@FunctionalInterface
, the compiler checks that it adheres to the rules of a functional interface.@FunctionalInterface
does not satisfy the conditions (e.g., has more than one abstract method), the compiler will raise a compilation error.Optional Annotation:
@FunctionalInterface
annotation is optional, using it provides clarity to both developers and tools about the intended use of the interface.Example:
Here is an example of a functional interface and its usage:
java@FunctionalInterface
interface MyFunctionalInterface {
void myAbstractMethod();
default void myDefaultMethod() {
System.out.println("Default method");
}
static void myStaticMethod() {
System.out.println("Static method");
}
}
public class FunctionalInterfaceExample {
public static void main(String[] args) {
// Using a lambda expression to implement the functional interface
MyFunctionalInterface myFunctionalInterface = () -> System.out.println("Abstract method implementation");
myFunctionalInterface.myAbstractMethod();
// Calling default and static methods
myFunctionalInterface.myDefaultMethod();
MyFunctionalInterface.myStaticMethod();
}
}
In this example, MyFunctionalInterface
is annotated with @FunctionalInterface
, and it has one abstract method (myAbstractMethod
). It also contains a default method and a static method.
SAM Interface:
Default Methods and @FunctionalInterface
:
java@FunctionalInterface
interface MyFunctionalInterface {
void myAbstractMethod();
default void myDefaultMethod() {
System.out.println("Default method");
}
}
In this example, MyFunctionalInterface
is a valid functional interface despite having a default method.
Using the @FunctionalInterface
annotation is a good practice when designing interfaces for functional programming in Java. It makes the intent explicit and enables the compiler to provide additional checks and guidance.