Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda Expression JAVA-8

Tags:

lambda

java-8

I have just started with JAVA 1.8 version and had a question while going through the tutorials regarding lambda expression.

Can we have more than 1 implementation(lambda expression) for the abstract method by creating multiple instances of the Interface WITHIN THE SAME CLASS??? I tried the code and it ran perfectly....

Now my question is that the very concept of interface is that every IMPLEMENTING CLASS WILL HAVE A DEFINITION FOR THE ABSTRACT METHOD. THEN HOW CAN WE HAVE TWO METHOD BODIES(lambda expressions) in the SAME CLASS ???

Consider the below code :

public static void main(String[] args) {

    Interf i = (a, b) -> a + b;
    System.out.println("The result is >> " + i.result(10, 20));

    Interf i1 = (a, b) -> a - b;
    System.out.println("The result is >> " + i1.result(10, 20));


}

Output:

The result is >> 30

The result is >> -10

like image 477
Lokesh Baranwal Avatar asked Jul 17 '26 20:07

Lokesh Baranwal


1 Answers

Each of your two lambda expressions implements your Interf functional interface separately. Therefore each implementation of that interface has a single implementation of that interface's single abstract method.

Even before Java 8 and lambda expressions you could create two anonymous class instances that implement your Interf interface. Each one of them would have a single implementation of Interf's single method.

The fact that the two lambda expressions are defined in the same class doesn't mean that the two implementations of the functional interface's abstract method belong to the same class.

like image 169
Eran Avatar answered Jul 23 '26 10:07

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!