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.
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.
Thread t1=new Thread(new Runnable() {
@Override
public void run() {
System.out.println("In Run method");
}
});
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.
// Using lambda expression
Thread t1=new Thread(
()->System.out.println("In Run method")
);
Lets see an example of functional interface,
@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.
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.