Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does an anonymous inner class always capture a reference to "this" (outer) object when accessing its primitives etc.?

If I have

[EDIT: added the type definition for "Inner"]

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 the call to inner.execute() set the outerInt variable of that particular Outer object to 5, wherever it is called from, and for as long as that Inner object exists? Or will it just change a copy of the outerInt variable and not affect the original Outer object?

like image 311
Navigateur Avatar asked Dec 21 '11 01:12

Navigateur


1 Answers

This will capture and modify the outer this.

See the spec

like image 135
SLaks Avatar answered Nov 06 '22 05:11

SLaks