Xiaokun
Xiaokun

Reputation: 874

How Java know which method should be override when use lambda expression

With JAVA8, inner class can be replaced with lambda expression.

Comparator c = (a, b) -> Integer.compare(a.length(), b.length());

Runnable java8Runner = () ->{System.out.println("I am running");};

How jvm know, this lambda should override the right method? In above examples, they are run() and compare().

Upvotes: 3

Views: 1188

Answers (2)

davidxxx
davidxxx

Reputation: 131466

Thilo is right.

Nevertheless, the term

Single-Method-Interfaces

is not the more appropriate because a functional interface may have multiple methods : potentially multiple default methods but one and single abstract method.
For example it is a valid functional interface :

@FunctionalInterface
public interface MyInterface {

    Integer getResult();
    default boolean isNoResult(){
       return getResult()==null;
    }
}

An expression lambda can be used only in the context of a functional interface. A functional interface is a Java interface specifying one and single abstract method. In your example, Comparator and Runnable have only one abstract method. More details here : https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html

How jvm know, this lambda should override the right method? In above examples, they are run() and compare().

If you use a lambda expression with a no functional interface, the compilation wil be in error : the compiler will indeed complain about it with the explicit message :
The target type of this expression must be a functional interface

So, even if it is not mandatory, if you create a interface in the aim being a functional interface, it is a good practice to declare it with the annotation @FunctionalInterface to enforce the compiler to check it is a valid functional interface : one and single abstract method. In this way, you would know right now when your interface is a functional interface valid or not.
That's why JDK classes in Java 8 does it.

Upvotes: 5

Thilo
Thilo

Reputation: 262734

This is facilitated by means of Single-Method-Interfaces. There is only a single (abstract) method in these interfaces. If there is ambiguity, the shorthand lambda syntax cannot be used.

You can use the @FunctionalInterface annotation to have the compiler enforce this for an interface (but it is not necessary, the interface can be used in lambdas even without it).

Upvotes: 7

Related Questions