下面的语句中:
class InOut
{
String str=new String ("Between");
public void amethod(final int iArgs)
{
int it315=10;
class Bicycle
{
public void sayHello()
{
System.out.println(str);
System.out.println(iArgs);
System.out.println(it315);//此处编译出错:InOut.java:13: local variable it315 is accessed from within inner class; needs to be declared final
System.out.println(it315);
^
}
}
}
}
为什么不能访问it315呢?System.out.println(it315);是在函数public void amethod(final int iArgs)的内部调用的it315呀,此时,it315的生命周期并没结束,为什么不能访问?
----------------解决方案--------------------------------------------------------
错误警告已经很明确的告诉你答案了
内部类要访问包装类的变量 该变量必须被定义为final的
----------------解决方案--------------------------------------------------------
我是想知道这是为什么
----------------解决方案--------------------------------------------------------
因为java中规定,内部类只能访问外部类中的成员变量,不能访问方法中定义的变量,如果要访问方法中的变量,就要把方法中的变量声明为final(常量)的,因为这样可以使变量全局化,就相当于是在外部定义的而不是在方法里定义的
----------------解决方案--------------------------------------------------------