【176期】面试官:你知道为什么要加 final 关键字了吗?
共 4845字,需浏览 10分钟
·
2021-04-14 07:19
阅读本文大概需要 2.8 分钟。
来自:www.jianshu.com/p/acc8d9a67d0c
现象描述
但是在 Java 8 之后,类似场景却没有再提示了:
难道是此类变量可以随便改动了吗?当然不是,当你试图修改这些变量的时候,仍然会提示错误:
可以看到,当试图修改基本数据类型的变量时,编译器的警告变成了“Varible 'num' is accessed from within inner class, need to be final or effectively final”,很遗憾,仍然不能修改。相比之下,Kotlin 是没有这个限制的:
原因分析
不难推断,这个 TestInnerClass$1.class 就是匿名内部类编译后的文件,看看它反编译后是什么内容:
class TestInnerClass$1 extends InnerClass {
TestInnerClass$1(TestInnerClass var1, int var2, DataBean var3) {
super(var1);
this.this$0 = var1;
this.val$num = var2;
this.val$bean = var3;
}
void doSomething() {
super.doSomething();
System.out.println("num = " + this.val$num);
System.out.println("bean name is: " + this.val$bean.name);
}
}
情景对比
public final void useNestedClass(@NotNull final TestNestedClass.DataBean bean) {
Intrinsics.checkParameterIsNotNull(bean, "bean");
final IntRef num = new IntRef();//---1
num.element = 1;//---2
String var3 = "before action, num = " + num.element;
System.out.println(var3);
<undefinedtype> nestedClass = new TestNestedClass.NestedClass() {
public void doSomething() {
num.element = 678;//---3
bean.setName("xyz");
String var1 = "num = " + num.element;
System.out.println(var1);
var1 = "bean name is: " + bean.getName();
System.out.println(var1);
}
};
nestedClass.doSomething();
String var4 = "after action, num = " + num.element;//---4
System.out.println(var4);
}
public final void useNestedClass(@NotNull TestNestedClass.DataBean bean) {
Intrinsics.checkParameterIsNotNull(bean, "bean");
int num = 1;
String var3 = "before action, num = " + num;
System.out.println(var3);
int num = 678;
var3 = "after action, num = " + num;
System.out.println(var3);
}
推荐阅读:
微信扫描二维码,关注我的公众号
朕已阅