Functional Interface in Java 8 with examples

 266 total views,  3 views today

In this tutorial let us learn about Functional interface in Java.

A functional interface is an interface which has a single abstract method.This concept has been introduced as part of Java 8.

Note: Abstract method is an unimplemented method.

A functional interface can have default and static methods. But, it should have only one abstract method.

Below is the example of functional interface.

public interface Animal
{
    void run();
}

The above interface is a valid functional interface since it has only one abstract method.

Below is another example.

public interface Animal
{
    void run();

    static void walk()
    {
        System.out.println("I am walking...");
    }

    default void talk()
    {
        System.out.println("I am talking...");
    }
}

The above is also a valid functional interface because it has only one abstract method. Default and static methods are not considered.

@FunctionalInterface

@FunctionalInterface can be used to impose a rule on the interface to have only one abstract method.

Let us look at an example.

@FunctionalInterface
public interface Vehicle
{
    void run();
}

The compiler will throw an error if the interface has more than one abstract method.

Invalid '@FunctionalInterface' annotation; Vehicle is not a functional interface

Exisiting java functional interfaces

  1. Runnable
  2. Comparable
  3. Consumer

Functional interface example

Let us define a functional interface with no arguments.

@FunctionalInterface
interface Animal {
    
    void run();
}
public class Test
{
    public static void main(String[] args)
    {
        Animal animal = () -> System.out.println("I am running...");
        animal.run();
    }
}

Let us define a functional interface with arguments.

@FunctionalInterface
interface Animal {
    
    void run(String obj);
}
  public static void main(String[] args)
    {
        Animal animal = (obj) -> System.out.println("I amrunning..."+obj);
        animal.run("faster");
    }

Refer official documentation.

This is how Functional interfaces can be used.Thanks for reading!Please provide your valuable comments.

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.