Search code examples
javainterfacepredicate

Java Predicate Interface - How the method is working - Though it is not implemented in my class


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);
}

Solution

  • 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.