Sunday, August 24, 2014

Functional Interface in Java

Functional interface are introduced in Java 8 and they simply mean that they have just one method declared in it. Nothing more nothing else.

One can annotate an interface with exactly one declared method as functional interface. It's not mandatory also to define the annotation as interfaces with only one declared method will be treated as functional interface. Functional interfaces are used in lambda expression. For example, Comparator is a functional interface.

Example of a Functional Interface

//Not a mandatory annotation, but good practise to stop
//someone to add new methods unknowingly
@FunctionalInterface
public interface MyFunctionalInterface {
    public void OnlyOneFunction();
}

Example of an interface which is not Functional Interface

//Uncommenting the functional interface annotaion will give compile error
// "Invalid '@FunctionalInterface' annotation; 
//   NotAFunctionalInterface is not a functional interface"
//@FunctionalInterface
public interface NotAFunctionalInterface {

public void firstFunction();
public void secondFunction();

}

No comments:

Post a Comment