Java Functional Interfaces
An Interface that contains exactly one abstract method is known as functional interface. It can have
any number of default, static methods but can contain only one abstract method. It can also declare
methods of object class.
Functional Interface is also known as Single Abstract Method Interfaces or SAM Interfaces. It is
a new feature in Java, which helps to achieve functional programming approach.
Example 1
1. @FunctionalInterface
2. interface sayable
3. {
4. void say(String msg);
5. }
6. public class FunctionalInterfaceExample implements sayable
7. {
8. public void say(String msg)
9. {
10. [Link](msg);
11. }
12. public static void main(String[] args)
13. {
14. FunctionalInterfaceExample fie = new FunctionalInterfaceExample()
15. [Link]("Hello there");
16. }
17. }
Output:
Hello there
A functional interface can have methods of object class. See in the following example.
Example 2
1.
2. @FunctionalInterface
3. interface sayable
4. {
5. void say(String msg); // abstract method
6. // It can contain any number of Object class methods.
7. int hashCode();
8. String toString();
9. boolean equals(Object obj);
10. }
11. public class FunctionalInterfaceExample2 implements sayable
12. {
13. public void say(String msg)
14. {
15. [Link](msg);
16. }
17. public static void main(String[] args)
18. {
19. FunctionalInterfaceExample2 fie = new FunctionalInterfaceExample2();
20. [Link]("Hello there");
21. }
22. }
Output:
Hello there
Invalid Functional Interface
A functional interface can extends another interface only when it does not have any abstract
method.
1. interface sayable
2. {
3. void say(String msg); // abstract method
4. }
5. @FunctionalInterface
6. interface Doable extends sayable
7. {
8. // Invalid '@FunctionalInterface' annotation; Doable is not a functional interface
9. void doIt();
10. }
Output:
compile-time error
Example 3
In the following example, a functional interface is extending to a non-functional interface.
1. interface Doable
2. {
3. default void doIt()
4. {
5. [Link]("Do it now");
6. }
7. }
8. @FunctionalInterface
9. interface Sayable extends Doable
10. {
11. void say(String msg); // abstract method
12. }
13. public class FunctionalInterfaceExample3 implements Sayable
14. {
15. public void say(String msg)
16. {
17. [Link](msg);
18. }
19. public static void main(String[] args)
20. {
21. FunctionalInterfaceExample3 fie = new FunctionalInterfaceExample3();
22. [Link]("Hello there");
23. [Link]();
24. }
25. }
Output:
Hello there
Do it now