πŸŽ‰ Special Offer !    Code: GET300OFF    Flat β‚Ή300 OFF on every Java Course
Grab Deal πŸš€

Functional Interfaces  


Introduction
  • A Functional Interface is an interface that contains exactly one abstract method.
  • They are also known as Single Abstract Method (SAM) interfaces.
  • They were introduced in Java 8 to support Lambda Expressions and Method References.
  • Functional Interfaces can be annotated with @FunctionalInterface (optional but recommended) to indicate that it must have only one abstract method.
  • Note:
    • Functional interfaces can have any number of default and static methods, but only one abstract method.
  • Uses of Functional Interfaces:
    • To enable writing more readable and maintainable code with less boilerplate.
    • To use Lambda Expressions for implementing abstract methods in a clean and concise way.
    • To represent functional programming constructs like function, predicate, supplier, consumer.
  • Some Predefined Functional Interfaces (in java.util.function package):
    • Runnable – No argument, no return value (used in multithreading).
    • Callable<V> – No argument, returns a value (used in multithreading).
    • Predicate<T> – Takes one argument and returns boolean.
    • Function<T,R> – Takes one argument and returns a value.
    • Consumer<T> – Takes one argument and returns nothing (void).
    • Supplier<T> – Takes no argument and returns a value.
Syntax:
  • Syntax of a Functional Interface:
    @FunctionalInterface
    interface MyInterface
    {
        // Single abstract method (SAM)
        void m1();
    
        // You can still have default or static methods
        default void m2()
        {
            System.out.println("Default method inside functional interface");
        }
    }
Program:
  • Program 1: Below is the program for Functional Interfaces:
    @FunctionalInterface
    interface MyInterface
    {
        void greet(String name);
    }
    
    class MyClass implements MyInterface
    {
        @Override
        public void greet(String name)
        {
            System.out.println("Hello, " + name + "!");
        }
    }
    
    public class MainApp3
    {
        public static void main(String[] args)
        {
            MyClass obj = new MyClass();
            obj.greet("Deepak");   // Calls the implemented method
        }
    }
  • Program 2: Below is an alternate approach for the above program:
    @FunctionalInterface
    interface MyInterface
    {
        void greet(String name);
    }
    
    public class MainApp3
    {
        public static void main(String[] args)
        {
            MyInterface mi = new MyInterface() {
                @Override
                public void greet(String name) {
                    System.out.println("Hello, " + name + "!");
                }
            };
            mi.greet("Deepak");
        }
    }