What is functional interface in java with examples?
A functional interface in java became popular with introduction of java 8 features like lambda expression.
A functional interface is an interface that contains one and only one abstract method in it.
Example of functional interface in java includes
Given below are examples of functional interface in java:
-
Comparable interface - it contains only compareTo(); abstract method
-
CompareTo interface - it contains only compare(); abstract method
-
Runnable interface - it contains only run(); abstract method
-
Callable interface - it contains only call(); abstract method
-
ActionListener interface - it contains only actionPerformed(); abstract method
Thus we can see that there is one similarity among all of them - 'all contains only 1 abstract methods'.
All of the above are functional interface provided by java.
Custom functional interface
However, if programmer wants they can create custom functional interface as shown below:
@FunctionalInterface
interface SayHello{
void sayHelloJava8(); //abstract method
}
From the above code we learn:
-
to mark an interface as functional interface, we can use @FunctionalInterface
-
create only one abstract method in it.
Our functional interface:
-
should not contain more than one abstract method, else compilation error will occur.
Suppose we write below code:
@FunctionalInterface
interface SayHello{
void sayHelloJava8();
void sayHelloJava9();
}
We will get compilation error - 'Invalid '@FunctionalInterface' annotation; SayHello is not a functional interface'
To remove this compilation error:
-
We should either delete one abstract method, or
-
delete the @FunctionalInterface annotation to make it non functional interface.
Functional inteface concept is heavily utilised in java 8.
In java 8, lambda expression provides implementation for functional interface as shown in below example code:
@FunctionalInterface
interface SayHello{
void sayHelloJava8();
}
public class Java8HelloWorld {
public static void main(String[] args) {
//lambda providing implementation to functional interface SayHello
SayHello hello = () -> System.out.println("Java 8 Hello World");
hello.sayHelloJava8();
}
}
OUTPUT
Java 8 Hello World
You can learn more about java 8 features and lambda expression in java 8 tutorial.
Would you like to see your article here on tutorialsinhand.
Join
Write4Us program by tutorialsinhand.com
About the Author
Sonu Pandit
Technology geek, loves to write and share knowledge with the world. Having 10+ years of IT experience. B.Tech in Computer Science & Engineering
Page Views :
Published Date :
Aug 03,2020