0

enter image description here

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
  • A functional interface is any interface that contains only one abstract method, but it may contain one or more default methods or static methods. You should study docs.oracle.com/javase/tutorial/java/javaOO/… Commented Feb 15, 2021 at 6:37
  • The @FunctionalInterface annotation 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 @FunctionInterface causes 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. Commented Feb 15, 2021 at 6:57

2 Answers 2

1

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";
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

@FunctionalInteface in Java is the interface with only one method.

https://www.baeldung.com/java-8-functional-interfaces

3 Comments

Clarification: With only one abstract method. It can have other methods, as long as they are default or static.
Yep. Default methods could exist
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.