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.
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.
@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:
This post was last modified on December 27, 2020