Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 461
Tiny Avatar asked Mar 21 '23 07:03

Tiny


1 Answers

It's described very well in this article:

.. the methods in an anonymous class don't really have access to local variables and method parameters. Rather, when an object of the anonymous class is instantiated, copies of the final local variables and method parameters referred to by the object's methods are stored as instance variables in the object. The methods in the object of the anonymous class really access those hidden instance variables. Thus, the local variables and method parameters accessed by the methods of the local class must be declared final to prevent their values from changing after the object is instantiated.

Also refer to the JLS - 8.1.3. Inner Classes and Enclosing Instances for details and further explanation.

like image 103
Maroun Avatar answered Apr 26 '23 18:04

Maroun