java中声明内部类变量_关于java:在方法中定义的内部类要求在方法中声明的变量是最终变量(如果从内部类内部访问它们)…

  • Post author:
  • Post category:java


本问题已经有最佳答案,请猛点这里访问。

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

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.”;

如果删除了final修饰符,则instantiate()方法内部的内容将导致如下编译时错误。

local variable localString is accessed from within inner class; needs

to be declared final

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

本文对此进行了很好的描述:

.. 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。 内部类和封闭实例的详细信息和进一步说明。

这是通过以下方式实现的:localString的值在构造时传递给内部类,并存储在内部隐藏字段中。 由于现在有该值的两个副本,因此如果您随时更改外部变量的值,将会非常混乱。 内部副本仍将具有构造内部类时所具有的旧值。

因此,Java要求将其声明为final,这样就不可能实现。



版权声明:本文为weixin_28761725原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。