Java 8 functional interface example

Java 8 functional interface example helps you answer some confused questions, e.g: what is functional interface? How to create a functional interface?. And how does a functional interface works in fact.

Java 8 functional interface example walks you through
What is functional interface

Functional interfaces are new additions in java 8 which permit exactly one abstract method inside them. These were intruduced to support lambda expressions, method reference and constructor references as well.
Here is a functional interface:

Java 8 provides an annotation @FunctionalInterface which can be used for compiler level errors when the interface you have annotated violates the rules of Functional Interface. Above example is with @FunctionalInterface:

Let’s try to add another abstract method into the functional interface we’re getting the compiler errors (on eclipse) like below:

Java 8 functional interface example

Java 8 functional interface example
We’re considering a example which compare using anonymous inner class with using lambda expression. The lambda expression is based on the above functional interface.

Above program provides output like below
Java 8 functional interface example


Below is list of things that you should remember about functional interface.

1)Functional interface permits exactly one abstract method inside. We can add another abstract method if we remove @FunctionInterface annotation, but it will make the interface is a non-functional interface.

2)The @FunctionalInterface annotation only notices the compiler to enforce single abstract method inside functional interface. A functional interface is valid even if the @FunctionalInterface annotation would be omitted as long as the interface has exactly one abstract method.

3) A functional interface can contain more than one default method since default methods have an implementation and they are not abstract.

4) If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface’s abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere.

Let’s see a valid functional interface below.

That’s all for this time regarding Java 8 functional interface example.

Functional Interface

Download complete source code, click link below (220 downloads)

Leave a Comment


Please share it if you found this useful
Hide Buttons