Inner classes defined within a method require variables declared in a method to be final if available from inner classes

The following code defines the class inside the 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();
    }
}

Call the method instantiate().

new OuterClass().instantiate();

The following statement

final String localString = "String in method.";

inside the method instantiate()causes a compile-time error if the modifier is finaldeleted .

The localString local variable is accessed from the inner class; needs will be announced final

Why local variable localStringmust be declared final, in this case?

+4
source share
2 answers

:

.. . , , final , , . . , , , .

. JLS - 8.1.3. Inner Classes Enclosing Instances .

+4

: localString . , , . , .

Java , , .

+3

All Articles