开发者

Java Inner Classes [duplicate]

开发者 https://www.devze.com 2023-03-10 08:20 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicates: Cannot refer to a non-final variable inside an inner class defined in a different method
This question already has answers here: Closed 11 years ago.

Possible Duplicates:

Cannot refer to a non-final variable inside an inner class defined in a different method

Why inner classes require开发者_JAVA技巧 “final” outer instance variables [Java] ?

class MyOuter {    

    private String x = "Outer";
    void doStuff(){
           final String z = "local variable";
           class MyInner {
                 public void seeOuter(){
                        System.out.println("Outer x is" + x);
                        System.out.println("Local variable z is" + z); // does
                        // not compile if final keyword from String z is removed
                 }
           }
     }
}

The above code works fine. I want to know why does the compiler give an error if I remove the final keyword from String z. What difference is the final keyword making?


Your class myInner cannot actually "see" the method scope variable z that you're referencing. The compiler just gives the inner class its own private copy of z. Thus if you were to change z later, your program could "break" in mysterious ways, since the code makes it "look like" it's the same variable.

Thus, the compiler will not let you write that code unless you promise you understand that z cannot change later, by declaring it final.


1) z is a reference to String that lives on the current Thread stack. Now, let's suppose that in your inner class you start a thread (B) and you want to access z from B. But B doesn't have access to A's stack. To allow this access, Java makes a copy of this reference. But to make sure that both threads will not change their own value, so that will put this system in inconsistent state, you have to declare it final.

0

精彩评论

暂无评论...
验证码 换一张
取 消