Functional Interface in Java 8 | Java 8
Functional interfaces are introduced in java 8. Functional interfaces are also known as SAM Interface(single astract method interfaces). Functional interfaces help us in writing simpler and smaller code using lambda-expressions which is also introduced in java 8.
What is Functional interface in java 8 ?
'Any interface having exactly one abstract method is called functional interface'. Java 8 has also introduced an annotation @FunctionalInterface which can be used while declaring functional interfaces in java to avoid compile time errors. This annotation ensures that the interface annotated with @FunctionalInterface should qualify the conditions to be a functional interface, otherwise compiler will throw an error.
Example of functional interface -package com.java8.interfaces; @FunctionalInterface public interface FunInterface { void printName(); }Above interface is a functional interface.
Notice that, we can can always declare a functional interface without using the @FunctionalInterface annotation.
Adding default methods in functional interface -
We can add any number of default methods in functional interface and it still will be a functional interface, the reason is obvious that default methods are not abstract methods hence adding a default method does not increase the count of abstract methods in functional interface.For example -
package com.java8.interfaces; @FunctionalInterface public interface FunInterface { void printName(); default boolean isFast(int speed){ return speed < 100 ? false : true; } default anotherMethod(){ //your code } }Above interface is also a function interface with two default methods in addition to the abstract method.
What if we overrides Object class's public methods in functional interface ?
A functional interface can always override any public method from the Object class.It does not count as another abstract
method in the interface and it still will be a functional interface.
For example we can take 'Comparator' a predefined interface in java is a functional interface even though it overrides
the Object class method 'equals()' in addition to the abstract method of its own.
We also can create one of ours like 'Comparator' which overrides the 'Object' class's method.For Example -
package com.java8.interfaces; @FunctionalInterface public interface FunInterface { void printName(); @Override boolean equals(Object arg0); @Override String toString(); }Above declared interface is still an functional interface, and we will not get any compilation error if we use annotation @FunctionalInterface with it.
So it was some detail about functional interface in java 8. In our next tutorial we will learn how to use java8 lambda expressions with functional interface. For any query, don't forget to comment below.
No comments :
Post a Comment