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:
That’s all about Java 8 Functional interface example.