-
在使用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();
}
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();