In the Lambda Expression tutorials, I introduced you to the Functional Interface and its importance when using Lambda Expression in Java code. In this tutorial, I will talk more about Functional Interface!
Definition of Functional Interface
OK, let me first talk about the definition of Functional Interface in the most complete and detailed way.
First of all, surely, the functional interface must be an interface.
For example:
1 2 3 4 |
package com.huongdanjava; public interface SayHello { } |
The second is that it has only one and only one abstract method. Lambda Expression will implement this abstract method.
For example, the following interface’s say() method is an abstract method:
1 2 3 4 5 |
package com.huongdanjava; public interface SayHello { void say(String name); } |
The third one is not mandatory, but you should know: we can use the @FunctionalInterface annotation to mark the class we want as a Functional Interface.
For example:
1 2 3 4 5 6 |
package com.huongdanjava; @FunctionalInterface public interface SayHello { void say(); } |
After an interface is marked with the annotation above, you cannot add another abstract method. If you try then a compile error will occur immediately.
Some Functional Interfaces in Java
From Java 7 and earlier, we have some interfaces that can be considered as Functional Interfaces from Java 8 onwards, such as:
FileFilter with only one abstract method:
1 |
boolean accept(File pathname); |
ActionListener also has an abstract method:
1 |
public void actionPerformed(ActionEvent e); |
From Java 8 onwards, Java provides us with more functionalities. They are defined in the java.util.function package:
You can find out more about them here.