Why do anonymous classes capture "this" even if they don't need to?

Because it is an inner class, and because

An instance i of a direct inner class C of a class or interface O is associated with an instance of O, known as the immediately enclosing instance of i. The immediately enclosing instance of an object, if any, is determined when the object is created (§15.9.2).

JLS 8.1.3.

There is no exception for 'even if they don't need to'.


  1. Because it is simpler to do it that way. Fewer code paths in the bytecode compiler, for example.

  2. Because if they treated the cases where this capture is necessary or unnecessary as different cases (i.e. by altering the effective constructor signature) then this would create huge problems for code that needs to create instances using reflection, byte-code engineering, etc.

Now the flipside of this is that it probably doesn't matter. The bytecodes are JIT compiled, and the JIT compiler should be capable of optimizing away unused variables (like this$0). If it is worthwhile to optimize away the passing of the hidden variable, this will be done by the JIT compiler as well.

Note this: You cannot make sound judgments on Java code efficiency by looking at the bytecode sequences. You really need to look at the native code emitted by the JIT compiler.


UPDATE - The stuff I wrote above about the JIT compiler's capability is speculative. However, if it turns out that there is a fundamental reason why the JIT compiler cannot optimize away an unused this$0, then that is most likely also a reason why the bytecode compiler can't do this either. (I am thinking of what happens when you debug the application.)