Is an anonymous inner class always capturing a reference to the "this" (external) object when accessing its primitives, etc.?

If i have

[EDIT: added type definition for "Internal"]

interface Inner{ public void execute(); } class Outer{ int outerInt; public void hello(){ Inner inner = new Inner(){ public void execute(){ outerInt=5; } } //later inner.execute(); } } 

will inner.execute() call set the outerInt variable of this particular Outer object to 5 , no matter where it is called, and as long as the Inner object exists? Or will it just change the copy of the outerInt variable and not affect the original Outer object?

+6
source share
4 answers

To answer your new clarified question (from a comment on my other answer):

Yes
All inner and local classes will have a reference to the this parent, even if they will never use it.
Demo

+3
source

This will capture and modify the external this .

See spec

+6
source

This is not necessarily the case. You did not show a class declaration for Inner. If Inner has a field called outerInt, then it will be changed. Otherwise, Outer outerInt will be. If you run:

 public class Outer { int outerInt = 0; public void hello() { Inner inner = new Inner() { @Override public void execute() { outerInt = 5; } }; // later inner.execute(); System.out.println(outerInt); } public static void main(String[] args) { Outer o = new Outer(); o.hello(); } } class Inner { int outerInt; public void execute() { } } 

You will get 0, not 5.

But by commenting outInIn in the Inner, you get 5

0
source

Yes Yes. But if you need to use an instance of an outer class, for example. going on to some method, you should say Outer.this.

0
source

Source: https://habr.com/ru/post/904207/


All Articles