Wednesday, 24 August 2016

Java8 - Functional Interface

  • An interface which only declare one abstract methods is a functional interface. Interfaces with single abstract also called SAM (Single Abstract Method) interface.
  • @FunctionalInterface annotation can be used to declare an interface functional.
  • If we put more than one abstract method and @FunctionalInterface in a same interface, it will give a compile time error.
  • If we are not putting @FunctionalInterface annotation than also any interface with single abstract is a functional interface.
  • Other than a single abstract method, other methods like Default and static methods can be declared in functional interface.
  • If an functional interface override any Object class methods, than also it will be a valid functional interface. For example Comparator interface declared two methods compare()  and equals(), but its a functional interface because equals() method is overrided from Object class.
  • Major benefit of functional interface is that functional interfaces can be instantiated by Lambda Expressions, which are simple and short than anonymous classes. I will create a new post for Lambda Expressions separately. 

Example of valid functional interfaces -  
Example 1 -
@FunctionalInterface
public interface ValidFunctionalInterface1 {
public void abstractMethod1();
}

Example 2 -
@FunctionalInterface
public interface ValidFunctionalInterface2 {
public void abstractMethod1();
public void defaultMethod1(){
System.out.println("This is a default method..")
}
}

Example of invalid functional interfaces -

@FunctionalInterface
public interface InvalidFunctionalInterface1 {
public void abstractMethod1();
public void abstractMethod2();
}

Above interface will thow a compile time error, InvalidFunctionalInterface1 is not a functional interface.

Example of valid but not functional interface -

public interface InvalidFunctionalInterface1 {
public void abstractMethod1();
public void abstractMethod2();
}

I hope Functional Interfaces concept is clear now. If you have any doubts please put in comments below. 

Difference between Comparable and Comparator in Java

No comments:

Post a Comment