Java 8 | Functional Interface

An interface which is having only one abstract method then it is called as a functional interface. (only one abstract method, one or more default methods or static methods)

Example:

package in.co.bitbyte.java8;

@FunctionalInterface

public interface Mobile {

public void makeCall();

}

We can use the annotation @FunctionalInterface to declare the interface as a functional interface. If it is not valid functional interface, Compiler will throw an error.

This annotation is optional. The compiler will consider interface as a functional interface if it contains exactly one abstract method.

Uses:

  • The functional interfaces are used extensively in lambda expressions.
  • The functional interface acts as a function. We can pass the interface as a parameter this is the functional programming approach.
  • So many interfaces in Java are functional interfaces (built in functional interfaces) like Comparator, Runnable and so on.
  • The main advantage of using functional interface is backward compatibility.

Note: we can declare abstract methods that are overriding the public methods of Object class. These methods did not consider as abstract methods in a functional interface. [Reason behind this thing is any implementation of the interface will have an implementation from Object class]

Example:

package in.co.bitbyte.java8;
@FunctionalInterface
public interface Mobile {  

public void makeCall(); 

public String toString(); 

boolean equals(Object obj);

static useInternetServices()
{
  System.out.println("use whats app");
}
default void mailServices()
{
System.out.println("Use e-mail service");
}

What do you think?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s