Hello guys. What is difference between FunctionInterface and Interface why we need declare
@FunctionalInterface if we have interface in this implementation of package java.util.function;
2 Answers
FunctionalInterface is an interface with :
- only one abstract method.
- zero or several default methods (with body).
Thus, the compiler will be able to find the method corresponding to the lambda you will pass.
Eg;
@FunctionalInterface
public interface Supplier<T> {
T get();
default String greet() {
return "Hello, World ";
}
default String greet2() {
return "Hello, World 2";
}
}
Thus java will easily find the right (abstract) method because is is unique.
Supplier<Car> fordCarProvider = () -> new Car("Ford", 1500, 4, 43000);
Supplier<Car> bmwCarProvider = () -> new Car("BMW", 1500, 4, 83000);
System.out.println(fordCarProvider.get());
System.out.println(bmwCarProvider.get());
But in case you have several abstract method, it is no more a FunctionalInterface. Because ambiguity might occur.
// No more @FunctionalInterface
public interface Supplier<T> {
T get();
String greet();
default String greet2() {
return "Hello, World 2";
}
}
Comments
@FunctionalInteface in Java is the interface with only one method.
3 Comments
Andreas
Clarification: With only one
abstract method. It can have other methods, as long as they are default or static.Oleg Cherednik
Yep. Default methods could exist
Holger
@Andreas further clarification, exactly one abstract method that does not match a signature of a public method of
java.lang.Object. But the annotation itself has a documentation and the language specification explains it, so we don’t need a link to baeldung.com that is infamous for sloppy or outright wrong articles whose sole purpose seems to be to give us more questions on Stackoverflow.
@FunctionalInterfaceannotation is strictly informational: it's never necessary to use it. The Java compiler can recognize functional interfaces with or without@FunctionInterface. Just speculating now, but possibly@FunctionInterfacecauses Javadoc to insert the blurb "Functional Interface: This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference." in the heading of the method's Javadoc page.