关于Java中本地最终变量的问题 [英] Question about local final variable in Java

查看:121
本文介绍了关于Java中本地最终变量的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

public class BookLib {
    void f() {
        final int x = 5; // Line 1
        class MyCLass {
            void print() {
                System.out.println(x);
            }
        }
    }
}

I不明白为什么在这种情况下应该使用最终变量(第1行)?

I don't understand why should use final variable in this case (Line 1)?

推荐答案

你在这里创建了一个内部类。由于此类对象的生命周期可能远大于方法调用的运行时(即对象在方法返回后很久仍然存在),它需要保留局部变量的状态可以访问。

You've created an inner class here. Since the life-time of objects of this class can potentially be much greater than the runtime of the method invocation (i.e. the object can still exist long after the method has returned), it needs to "preserve" the state of local variables that it can access.

这种保留是通过在内部类中创建(不可见的,合成的)副本并使用对该副本的引用自动替换对局部变量的所有引用来完成的。在创建内部类对象后修改局部变量时,可能会导致奇怪的效果。

This preserving is done by creating an (invisible, synthetic) copy inside the inner class and automatically replacing all references to the local variable with references to that copy. This could lead to strange effects when the local variable were modified after the inner class object was created.

为避免这种情况,有一个要求您以这种方式访问​​的所有局部变量都是 final :这可以确保局部变量只有一个可能的值,并且没有观察到任何不一致。

To avoid this, there is a requirement that all local variables that you access this way are final: this ensures that there is only ever one possible value for the local variable and no inconsistencies are observed.

此特定规则可在§8.1.3内部类和附加实例 noreferrer> JLS :

This specific rule can be found in §8.1.3 Inner Classes and Enclosing Instances of the JLS:


使用但未在内部声明的任何局部变量,形式方法参数或异常处理程序参数必须将类声明为final。必须明确分配在内部类中使用但未声明的任何局部变量(§16)在内部阶级的主体之前。

Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final. Any local variable, used but not declared in an inner class must be definitely assigned (§16) before the body of the inner class.

这篇关于关于Java中本地最终变量的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆