Powered by Blogger.

Thursday 23 June 2022

Functional Interface in Java

No comments :
Introduction
An Interface which has only one abstract method (SAM: Single Abstract Method) is called Functional Interface. It is used annotation @FunctionalInterface: An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification. Conceptually, a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere.

@FunctionalInterface 
 interface adition{
 void add(int a, int b); 
 }

Runnable, ActionListener, Comparable, Comparator, Callable Are some of the examples of functional interface. There is no need to use the abstract Keyword as it is optional to use the interface
why use Functional Interface?
    It is used for enabling functional programming to java language. Functional Interface is also used for defining Lambda Expressions to Pass a function directly as argument to method.

package com.a143mk.SpringBoot.interfaces; 
public class Java8InmlInterfaceLambda { 
public static void main(String[] args) { 
// lambda expression to create the object 
new Thread(() -> { System.out.println("New thread created Lambda"); }).start();
 }
 }

Some Other Functional Interfaces
  • Consumer Interface
  • Predicate Interface 
  • Marker Interfaces
Consumer Interface:  Consumer interface has no return value it returns nothing. there are functional variables of the consumer -DoubleConsumer, IntConsumer and LongConsumer. These variables accept primitives values as arguments.

Predicate Interface : it is a functional interface whose functional method is test(obj), that takes an argument and return boolean value.

The predicate functionl interface can also be implemented using a class.
class ClassNme implements Predicate {}

Marker Interfaces: Marker Interface is an empity interface (no field or argument).
Marker Interface are serializable, cloneable and remote interface. All these interfaces are empity interfae.