Lambda Body and `this`

Marcio EndoMarcio EndoApr 28, 2025

In Java, a lambda body is transparent to the meaning of this. For example, the following program will print Hello, World! when executed:

private Runnable runnable = () -> {  System.out.println(this); };@Overridepublic String toString() {  return "Hello, World!";}void main() {  runnable.run();}

But, if we replace the lambda expression with an anonymous inner class, it prints InnerClassThis$1@568bf312 on my machine:

private Runnable runnable = new Runnable() {  @Override public void run() {    System.out.println(this);  }};@Overridepublic String toString() {  return "Hello, World!";}void main(String[] args) {  runnable.run();}

So, we can say that a lambda expression is something less than a class of its own: it has no concept of this. In a lambda body, this refers to the enclosing context. Here's the formal spec:

The value denoted by this in a lambda body (§15.27.2) is the same as the value denoted by this in the surrounding context.

If you want to learn more about lambda expressions in Java, you should read this document.