In this post , we are going to see about functional interface in java. It is closely related to java lambda expressions.
Functional interfaces are those interfaces which have only one abstract method, it can have default methods, static methods and it can also override java.lang.Object class method.
There are many functional interfaces already present.
For example: Runnable , Comparable.
You can implement functional interfaces using lambda expressions.
Let’s understand with classic example of Runnable:
When we need to create a Thread and pass an anonymous Runnable interface, we can do it as follow.
Above method is old method of creating thread. As we have single abstract method in Runnable interface , we can consider it as functional interface, hence we can make use of lambda expression.
Lets see an example of functional interface,
Functional interfaces are those interfaces which have only one abstract method, it can have default methods, static methods and it can also override java.lang.Object class method.
There are many functional interfaces already present.
For example: Runnable , Comparable.
You can implement functional interfaces using lambda expressions.
Let’s understand with classic example of Runnable:
When we need to create a Thread and pass an anonymous Runnable interface, we can do it as follow.
1 2 3 4 5 6 7 8 |
Thread t1=new Thread(new Runnable() { @Override public void run() { System.out.println("In Run method"); } }); |
1 2 3 4 5 6 |
// Using lambda expression Thread t1=new Thread( ()->System.out.println("In Run method") ); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
@FunctionalInterface public interface Decorable { // one abstract method void decorateWithCurtains(); // default method default void decorateWithPaints() { System.out.println("Decorating using paints"); } // Overriding method of java.lang.Object @Override public int hashCode(); } |
Java can itself identify Functional Interface but you can also denote interface as Functional Interface by annotating it with @FunctionalInterface. If you annotate @FunctionalInterface, you should have only one abstract method otherwise you will get compilation error.
1 2 3 4 5 6 7 8 9 10 11 12 |
package org.arpit.java2blog; public class DecorableMain { public static void main(String[] args) { // Using lambada expression Decorable dec=()->{System.out.println("Decorating with curtains");}; dec.decorateWithCurtains(); } } |
When you run above program, you will get below output:
Decorating with curtains
That’s all about Java 8 Functional interface example.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.