https://blog.csdn.net/qq_22343483/article/details/100730115
https://blog.csdn.net/weixin_55038914/article/details/126541724
一.
-
非静态内部类是可以修改外部类属性的值的
public class Test1 {public String name = "abc";
public class Inner {
public Integer ager = 11;public void t1() { name = "bbb"; System.out.println(name); }
}
}
非静态内部类是拿不到外部类的局部变量的,所以就不存在不能修改外部类的局部变量的值的情况
-
只有匿名内部类使用基本类型的局部变量会出现这种问题
public class Test2 {
public static void main(String[] args) {
int a = 1;Thread thread = new Thread() { @Override public void run() { a = 2; //编译报错 } };
}
}
- 引用类型不会报错,因为引用类型的变量创建是在堆里面,方法结束,并不会消失
public class Test2 {
public static void main(String[] args) {
final ArrayList<Integer> objects = new ArrayList();
objects.add(1);
objects.add(2);
objects.add(3);
Thread thread = new Thread() {
@Override
public void run() {
for (int i = 0; i < objects.size(); i++) {
System.out.println(objects.get(i));
}
objects.add(11); //不会编译报错
for (int i = 0; i < objects.size(); i++) {
System.out.println(objects.get(i));
}
}
};
thread.start();
}
}