您的位置:首页 > Web前端

Cannot refer to a non-final variable * inside an inner class defined in a different method"错误解析

2014-01-22 22:58 781 查看
在使用Java局部内部类或者匿名内部类时,若该类调用了所在方法的局部变量,则该局部变量必须使用final关键字来修饰,否则将会出现编译错误“Cannot refer to a non-final variable * inside
an inner class defined in a different method” 下面通过一段代码来演示和分析原因。

[java]

public class Example {

public static void main(String args[]) {

doSomething();

}

private static void doSomething() {

final String str1 = "Hello";

// String str2 = "World!";

// 创建一个方法里的局部内部类

class Test {

public void out() {

System.out.println(str1);

// System.out.println(str2);

}

}

Test test = new Test();

test.out();

}

}

上面代码若去掉第9行和第14行的注释符号,则第14行就会给出“Cannot refer to a non-final variable * inside an inner class defined in a different method”这样的编译错误。原因如下:在方法中定义的变量时局部变量,当方法返回时,局部变量(str1,str2)对应的栈就被回收了,当方法内部类去访问局部变量时就会发生错误。当在变量前加上final时,变量就不在是真的变量了,成了常量,这样在编译器进行编译时(即编译阶段)就会用变量的值来代替变量,这样就不会出现变量清除后,再访问变量的错误。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐