0

Though I have not implemented the method - test - which is in Predicate interface, how come the method is executed without any body in my class - inte??

package newone; 
import java.util.function.Predicate;

public class inte {
    public static void main(String[] args) {
        Predicate <Integer> p = i -> (i<19);
        System.out.println(  p.test(22));
       }


@FunctionalInterface
public interface Predicate<T> {
    boolean test(T var1);
}
3

2 Answers 2

4

Though I have not implemented the method - test

You have, with the lambda expression:

Predicate <Integer> p = i -> (i<19);

That's mostly like:

Predicate<Integer> p = new Predicate<Integer>() {
    @Override
    public boolean test(Integer i) {
        return i < 19;
    }
};

The exact details in the bytecode are a little different, but for the most part you can think of a lambda expression as shorthand for creating an anonymous inner class. The compiler is able to perform other tricks to avoid creating extra classes in reality, at least in some cases - it depends on what your lambda expression does.

1
  • Thanks, this has puzzled me a lot! And this solved many of my other questions about Anonymous classes and functional interfaces as well. Feb 13, 2021 at 7:24
3

Newer compiler1, starting with version 8 (I believe), add a (synthetic) method to the code, mostly like:

public class Inte {
    public static void main(String[] args) {
        Predicate<Integer> p = Inte::lambda$test$1;
        ...
    }
    // synthetic
    private static boolean lambda$test$1(Integer i) {
        return i < 19;
    }
}

1 - alternatively, and before Java version 8, an additional class implementing the interface can be added (like an anonymous class)

3
  • I specifically say "the exact details in the bytecode are a little different" - the use of an anonymous class is to make it easier to understand how this is implementing an interface. I would suggest that this answer just moves the question on from "how does a lambda expression implement an interface" to "how does a method reference implement an interface". (I've added a little bit more detail to the end of the answer though.)
    – Jon Skeet
    Feb 13, 2021 at 8:27
  • @Jon I am not trying to compete with you, sorry (shouldn't be any problem for you to change or delete this answer - even if it wasn;t marked as community wiki)
    – user14971157
    Feb 13, 2021 at 8:47
  • No problem - I'm sorry for getting overly defensive, too.
    – Jon Skeet
    Feb 13, 2021 at 8:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.