Functional Interface:
→Interface with a single abstract method.
→Can have more than one default method.
You can check my post about the difference between abstract class and an interface here:
https://sairohithkaranam.blogspot.com/2020/04/what-is-abstract-class.html
→The implementation of the abstract method of the functional interface can be done in two ways
→Traditional way
→Lambda Expressions
→In this post, we will see both the ways.
Functional interface via Traditional way:
@FunctionalInterface //Optional
interface A
{
public void m();//abstract by default, one and only abstract method must be there
default void m1()//default method
{
System.out.println("The Developing Minds");
}
}
class Demo implements A
{
public void m()
{
System.out.println("Hello people!");
}
public static void main(String...args)
{
Demo d=new Demo();
d.m();
d.m1();
}
}
Output:
Hello people!
The Developing inds
Functional interface via Lambda Expressions:
@FunctionalInterface //Optional
interface A
{
public void m();//abstract by default, one and only abstract method must be there
default void m1()//default method
{
System.out.println("The Developing Minds");
}
}
class Demo
{
public static void main(String...args)
{
A a=()→System.out.println("Hello people!");//Lambda Expression!
a.m();
a.m1();
}
}
Output:
Hello people!
The Developing Minds
Now after seeing these two codes, you've understood what is the basic syntax of lambda expressions and how it is used.
Remember!
→()
These brackets in lambda expression indicate the parameter of the method.
→After the arrow(→) of the lambda expression, that was your actual implementation of the abstract method.
→So, the lambda expression, "()→System.out.println("Hello people!")" indicates that a method with no parameters is implementing a print statement. Cool, isn't it?
Though both methods give the same output, we prefer to choose lambda expressions often. Why?
Advantages of using Lambda Expressions over Traditional way:
→Faster
→Multiple implementations of a single method in Functional interface.
→In the above example, we can also write another implementation of the method 'm'.
class Demo
{
public static void main(String...args)
{
A a=()→System.out.println("Hello people");//Lambda Expression
//This line can also be shortened like this: A a=System.out.println("Hello people!");
A a1=()→System.out.println("Hello world");//Second implementation of same method
a.m();
a1.m();
}
}
Output:
Hello people!
Hello world
crux points:
- A functional interface is nothing but an interface with a single abstract method.
- We often use Lambda expressions for the implementation of abstract methods in the functional interface because it is faster.
- There are many inbuilt functional interfaces in java like Runnable, Comparable, ActionListener.
Comments
Post a Comment