Sam
Sam

Reputation: 2432

How final variables in method can be accessed by Inner class even if method goes out of scope?

I have already gone through many links for this answer. And I know that syntactically Java does not allow non-final variables to be accessed in Inner classes. According to this link, I have also understood that making a local-variable final allows it to stay alive even if the method gets completed and local variable goes out of scope.

But if a method goes out of scope how making it final would allow it to be alive for Inner classes where it has been referenced?

I am referring to the below code.

public class Outer {
    public static void outerMethod() {
        int methodVariable = 40;
        class Inner {
            public void innerMethod() {
                System.out.println(methodVariable); // This line produces compile time error.
            }
        }
    }
}

Upvotes: 0

Views: 42

Answers (1)

lexicore
lexicore

Reputation: 43661

If you check an instance of the Inner class in a debugger, you'll spot that there is a field for methodVariable:

Instance of Inner class in a debugger

Not that it is the only possible implementation, but it seems the compiler actually creates a private field for methodVariable and copies the value of the variable there.

This is probably also why the variable must be final or effectively final. If the value of the variable changes, this can't longer be synchronized with the value of the field.

Upvotes: 2

Related Questions