Java 8 functional interface example

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.
Lets understand with classic example of Runnable:
When we need to create a Thread and pass 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

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012