Inner classes defined within a method require variables declared in the method to be final, if they are accessed from within the inner classes

Viewed 505

The following code defines a class within a method.

final class OuterClass
{
    private String outerString = "String in outer class.";

    public void instantiate()
    {
        final String localString = "String in method."; // final is mandatory.

        final class InnerClass
        {
            String innerString = localString;

            public void show()
            {
                System.out.println("outerString : "+outerString);
                System.out.println("localString : "+localString);
                System.out.println("innerString : "+innerString);
            }
        }

        InnerClass innerClass = new InnerClass();
        innerClass.show();
    }
}

Invoke the method instantiate().

new OuterClass().instantiate();

The following statement,

final String localString = "String in method.";

inside the instantiate() method causes a compile-time error as follows, if the final modifier is removed.

local variable localString is accessed from within inner class; needs to be declared final

Why does the local variable localString need to be declared final, in this case?

2 Answers
Related