简体   繁体   中英

Could any one please tell me the scope of the Anonymous block in java?

I suspect that the JVM maintains a seperate copy of all outer class global variable for an anonymous block.Is it true?. Thanks for helping me.

Do you mean an anonymous class?

If an instance of an anonymous class is created in a non-static context then it will contain an implicit reference to instance of the outer class which created it. The anonymous instance will have access to the private fields and methods of the outer class. Though name clashes will be resolved in favour of the anonymous class.

To access fields and methods where there is a name clash use the following syntax:

OuterClass.this.methodCall();

Example:

public class Outer {

    public static void main(String[] args) {

        Outer o1 = new Outer(1);
        Outer o2 = new Outer(2);

        o1.doSomething();
        o2.doSomething();

    }

    private int i;
    private int j = 10;

    public Outer(int i) {
        this.i = i;
    }

    public void doSomething() {
        new Runnable() {

            private int i = 0;

            public void run() {
                System.out.println("Inner i = " + i);
                System.out.println("Outer i = " + Outer.this.i);
                System.out.println("Outer j = " + j);
            }
        }.run();
    }
}

You can modify objects outside of an anonymous inner class if they are mutable. However, you cannot reassign them because they must be declared final.

I interpreted your question to be asking: "When an anonymous block changes variables that are declared outside of the block, will the variables keep these changes after the block ends?"

I created a small test program to demonstrate the results:

public class AnonymousTest {
    private static int i = 0;
    public static void main(String[] args) {
        int j = 0;
        System.out.println("Before anonymous block: i=" + i + " j=" + j);

        //begin anonymous block
        {
            i = 5; j = 5;
            System.out.println("Inside anonymous block: i=" + i + " j=" + j);
        }
        //end anonymous block

        System.out.println("After anonymous block: i=" + i + " j=" + j);
    }
}

The output is:

Before anonymous block: i=0 j=0
Inside anonymous block: i=5 j=5
After anonymous block: i=5 j=5

As you can see, any variables modified inside of an anonymous block remain modified, so the JVM is not creating a copy of the variables for the anonymous block. However, variables declared inside an anonymous block belong to that block only, and are destroyed at the end of the block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM