gpt4 book ai didi

java - 错误 : local variable a is accessed from within inner class; needs to be declared final

转载 作者:行者123 更新时间:2023-11-30 08:18:37 34 4
gpt4 key购买 nike

class Outer
{
void m1()
{
int a=12;
class Inner
{
void show()
{
System.out.println(a);
}
}
new Inner().show();
}

}

在这里,当我编译这段代码时,我得到了从内部类中访问局部变量 a 的错误;需要声明为final。但是这里“int a”是一个局部变量,所以为什么我们需要声明为 final 以便在内部类中访问。

最佳答案

如果在内部类中使用局部变量,则需要将其声明为 final。对于要在此类内部类中使用的局部变量,Java 在幕后获取局部变量的副本并将其变成隐式实例变量,以便内部类可以访问它。因为它是副本,所以如果值发生变化,副本可能是错误的。因此,编译器会强制您使其成为 final

请注意,在 Java 8 中,这会编译,因为 a 是“有效最终的”——未声明 final,但一旦初始化就永远不会改变。

Section 8.1.3 of the JLS状态:

Any local variable, formal parameter, or exception parameter used but not declared in an inner class must either be declared final or be effectively final (§4.12.4), or a compile-time error occurs where the use is attempted.

Section 4.12.4 of the JLS状态:

A local variable or a method, constructor, lambda, or exception parameter is effectively final if it is not declared final but it never occurs as the left hand operand of an assignment operator (§15.26) or as the operand of a prefix or postfix increment or decrement operator (§15.14, §15.15).

In addition, a local variable whose declaration lacks an initializer is effectively final if all of the following are true:

  • It is not declared final.

  • Whenever it occurs as the left-hand operand of an assignment operator, it is definitely unassigned and not definitely assigned before the assignment; that is, it is definitely unassigned and not definitely assigned after the right-hand operand of the assignment (§16 (Definite Assignment)).

  • It never occurs as the operand of a prefix or postfix increment or decrement operator.

关于java - 错误 : local variable a is accessed from within inner class; needs to be declared final,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27429992/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com