What The Hell Is Functional Interface?

 A functional interface is an interface that contains only one abstract method. From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface.

Now Many people would be wondering like if we are allowed with only one abstract method in an interface from Java 8 Onwards it would be much more difficult for us to handle other methods we would then have to go for abstract class instead.

Wait a minute functional interface restricts you to single abstract method only if you use the annotation @FunctionalInterface , its not mandate to have the annotation with the interface its only to restrict more then one abstract method in the interface.

Now dont get confused in between interface in java8 and functional interface in java8.

Both are same just that one restricts you to single abstract method.

Now we also have static and default methods in the new interface in java8 which helps us implement our methods within the interface which wasnt possible in previous Java7 version.

Also the daimond problem we had earlier in previous version with the interfaces is resolved now.

So basically you just need to call the super with the method of that specific interface you implemented.


Now lets dive into the example for the functional interface.


So I have taken an example of finding whether the number is even or odd number.

I am using lamda expression to verify whether number is even or odd.

Now there is an inbuilt functional interface provided by java8 and that is predicates which can be used if you dont want to write your own custom functional interface.

I have a separate blog for predicates example.


@FunctionalInterface

interface EvenOrOdd {

String findNumberIsEvenOrOdd(int x);

}


class FunctionInterfaceExample {

public static void main(String args[]) {

int input = 5;


EvenOrOdd output = x -> x % 2 == 0 ? "even number" : "odd number";


System.out.println(output.findNumberIsEvenOrOdd(input));

}

}


 

Comments

Popular posts from this blog

3 Lines of Code And You Can Download Your Favourite Youtube Video.

Leetcode Problem(Easy) Roman to Integer

Leetcode : (Find Minimum in Rotated Sorted Array)