Java-8 Functional Interface

Java Functional Interface



If look into some other programming languages like c++, Javascript they are called functional programming languages bcoz, we can write functional and use whenever required.

An interface with only 1 abstract method is called Functional interface.
A new annotation @FunctionalInteface provides us to avoid accidental addition od abstract methods.
Functional interface is long waited and much sought out feature of Java-8 as it enables us to use Lambda expressions to instantiate them.

Being object-oriented is not bad, but when we wanted to implement Runnable we do it as follows

Eg: 


1
2
3
4
5
Runnable r = new Runnable(){
   @Override
   public void run() {
    System.out.println("My Runnable");
   }};

If you notice it, the important logic in under run() method right?

Java-8 lambda expressions allow to help us in writing smaller and cleaner code.


Lambda Expressions:

Lambda expression is way through we can visualize functional programming in java object world.
Objects are base of java prog. Lang. and we can never have a function without an Object


Syntax:  (argument) -> (body)


1
Runnable r1 = () -> System.out.println("My Runnable");


In the above code, Runnable is a functional interface so we can use Lambda.
Since run() has no arguments,  we have no arguments passed.

Advantages of Lambda expressions:
  1. Reduced lines of code.
  2. Pass method into behaviours
  3. High efficiency 

No comments:

Post a Comment