其他
终于明白为什么要加 final 关键字了!
点击上方“后厂村码农”,马上关注,
每天早上9:10准时推送l
来源:www.jianshu.com/p/acc8d9a67d0c
现象描述
原因分析
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);
}
}
情景对比
但是为什么对于 Kotlin 来说可以在匿名内部类中直接修改基本数据类型的值呢?查看 Kotlin 编译后反编译回来的内容:
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);
}
说句题外话,有不少人想加皇叔微信,皇叔姑且放出来,但是坑位有限哦
推荐阅读
(点击标题可跳转阅读)
Google 出品的 Java 编码规范,强烈推荐,既权威又科学!
为什么程序员都不喜欢使用switch,而是大量的 if……else if ?
给公号“后厂村码农”加个星标吧,方便阅读。
喜欢就给个“在看”