0

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.
            }
        }
    }
}
3
  • 1
    The Inner class has a reference to its' scope. Commented Mar 17, 2018 at 17:27
  • @Elliott Can you please elaborate your answer? Commented Mar 17, 2018 at 17:30
  • The code in the question actually compiles now, although this has no bearing on your question of how the inner class is able to access the variable after the method returns. Commented Mar 17, 2018 at 17:30

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.