Java 8 Feature – Functional Interface

Functional Interface feature is added in Java 8. Java 8 is one of the major release of Java in which many useful features are added.

Java Interface which has ONLY ONE Abstract method is called Functional Interface. It is also called as Single Abstract Method – SAM.

Annotation –

@FunctionalInterface

@FunctionalInterface is used to indicate the Interface as Functional Interface. Interface annotated with this annotation, shall have only one abstract method. Incase it has more than one abstract method, it will result into compiler error.

Example –

Java Program of Functional Interface –

package com.thinkconstructive;

@FunctionalInterface
interface Welcome {
    public void welcomeMessage();
    default void methodOne(){
        System.out.print("Hello One");
    }
    default void methodTwo(){
        System.out.print("Hello Two");
    }
}

public class DemoFI {
    public static void main(String[] args) {
        Welcome welcome = () -> System.out.print("Welcome Interface is implemented");
        welcome.welcomeMessage();
    }
}

Output of the above program –

Welcome Interface is implemented

In the above example, welcomeMessage() is an abstract method and other 2 methods are concrete methods. In the main class welcomeMessage() is implemented with the help of Lambda Expression.

Note: A Functional Interface can extend another Interface when it doesn’t have any abstract method other it will result into compiler error.

Built In Functional Interface

Java provides many builtin Functional Interfaces; some important Functional Interfaces are mentioned below –

  1. Runnable
  2. Callable
  3. Comparator
  4. Function
  5. PathMatcher
  6. Callback
  7. Builder
  8. Consumer
  9. Supplier
  10. Consumer

Video Tutorial of Functional Interface is available HERE

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *