java - 方法中定义的内部类要求在方法中声明的变量是最终的,如果它们是从内部类中访问的

标签 java inner-classes final

<分区>

以下代码在方法中定义了一个类。

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();
    }
}

调用方法instantiate()

new OuterClass().instantiate();

下面的语句,

final String localString = "String in method.";

instantiate() 方法内部会导致如下编译时错误,如果 final 修饰符被删除

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

在这种情况下,为什么局部变量 localString 需要声明为 final

最佳答案

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.

另请参阅 JLS - 8.1.3. Inner Classes and Enclosing Instances了解详情和进一步解释。

关于java - 方法中定义的内部类要求在方法中声明的变量是最终的,如果它们是从内部类中访问的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20583056/

相关文章:

java - java中的继承和数组列表

Python数据结构/对象来建模静态多维表

java - Java 类中可以有或不能有内部接口(interface)有充分的理由吗?

java - 使用反射更改 Long.MIN_VALUE

java - classcastexception : cant be cast to com. sun.jersey.spi.container.servlet.ServletContainer

java - 正则表达式或字符串操作从字符串派生自动模块名称

java - Spring Security SAML 中的刷新 session

java - 什么时候使用(匿名)内部类是安全泄漏的?

java - 内部类非final变量java

java - 在 Java 中使用数组而不是 int 来处理 "potentially final variable"。