Alex Rivera | Logout

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

Asked 2011-12-21T01:01:08.880
8

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?

Edit
Report

1 Answer

0

This is not necessarily true. You didn't show is the class declaration for Inner. If Inner has a field called outerInt, then that one will be modified. Otherwise Outer's outerInt will. 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 out outerInt in Inner, then you get 5

answered 2011-12-21T01:59:03.227

Your Answer