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]

StackOverflow https://stackoverflow.com/questions/20583056

  •  01-09-2022
  •  | 
  •  

문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

This is implemented in the following way: the value of localString is passed to the inner class on construction and stored there in a hidden field. Since there are now two copies of the value it would be very confusing if you changed the value of the outer variable at any point. The inner copy would still have the old value it had when the inner class was constructed.

Therefore, Java requires it to be declared final so that this is not possible.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top