How Memory assigns to lambda | How does it refered,by non super class reference variable

Viewed 1886

I was creating the implementation of a functional interface, below is my code:

Consumer<Integer> consumer = new Consumer<Integer>() {
    @Override
    public void accept(Integer t) {
        System.out.println(t);
    }
};

As per the Java Documentation (javadoc)

A variable of a class type T can hold a null reference or a reference to an instance of class T or of any class that is a subclass of T.

In the code above, the anonymous object is created, which is a subclass of Consumer, and can be referred to by reference variable consumer, which is fine.

But I saw Consumer is a FunctionalInterface, so I can also do something like this in Java 8:

Using Lambda

Consumer<Integer> consumer = t -> System.out.println(t);

OR Using Method Reference

Consumer<Integer> consumer = System.out::println;

From what I know, no sub classes or anonymous classes are being created in both of the above cases. This result leaves me with two confusions:

1 : In the result of the lambda test, the variable consumer is not referring to subclass or Anonymous class of Consumer, so isn't this violating the above mentioned concept variable which can only refer child/self or null?

2 : How is memory assigned to lambdas, and how does the JVM handle such at run time?

3 Answers
Related