functional interface – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sun, 27 Dec 2020 15:01:03 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg functional interface – Programmerbay https://programmerbay.com 32 32 What is Functional Interface in Java 8 https://programmerbay.com/functional-interface-in-java-8/ https://programmerbay.com/functional-interface-in-java-8/#respond Sun, 14 Jun 2020 15:48:03 +0000 https://programmerbay.com/?p=6430 Programming languages such as Python, Scala that support functional programming , require few lines to complete a particular functionality, therefore, they are concise, on the flip side, Java can do the same thing but requires more lines of code.

In other words,one of the drawback of Java was that even a single functionality one require to create a method and that method is intended to be invoked by a class object. That certainly increases the length of the code.

To compete with other languages, Java developers decided to have functional programming as a new feature in Java.

To achieve this, Functional interface, Lambda Expressions (other alternatives such as Method reference and constructor references ) and many other features were introduced.

Functional Interface

A functional interface can be defined as an interface that consists exactly a single abstract method. However, it can have any number of static or default methods.

In order to use or implement Lambda expression, it is compulsory to use functional interface. A functional Interface is responsible for invoking Lambda expressions.

We cannot write Lambda expression without providing functional interface.

Functional Interface Annotation

@FunctionalInterface annotation is used to explicitly tell the compiler that a particular interface is intended to be a functional interface. A compiler triggers an error when a particular interface doesn’t satisfy the criteria of having a functional interface.

Runnable,Collable, Comparable are some examples of Functional interface.

A functional interface uses lambda expressions, method references or constructor references as one of the ways of its instance creation.

@FunctionalInterface
interface MyFunctionInterface{
        boolean compareMe(int a,int b);
        }



public class FunctionInterfaceExample {
    public static void main(String[] args) {
        int num=9,num1=8;
        MyFunctionInterface i = (a,b) ->  a>b;
       if(i.compareMe(num,num1))
           System.out.println(num+" is greater than "+num1);
       else
        System.out.println(num+" is smaller than "+num1);
    }
}

Output:

ouput

]]>
https://programmerbay.com/functional-interface-in-java-8/feed/ 0