为什么我们在匿名内部类中使用 final 关键字? [英] Why do we use final keyword with anonymous inner classes?

查看:24
本文介绍了为什么我们在匿名内部类中使用 final 关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在准备 S(O)CJP,与 Sierra &贝茨书.

I'm currently preparing the S(O)CJP, with the Sierra & Bates book.

关于内部类(本地方法或匿名方法),他们说我们不能访问局部变量,因为它们存在于堆栈中,而类存在于堆中并且可以被方法返回,然后尝试访问到这些在堆栈上但由于方法结束而不再存在的变量...

About inner classes (method local or anonymous), they say that we can't access the local variables because they live on the stack while the class lives on the heap and could get returned by the method and then try to have access to these variables that are on the stack but do not exist anymore since the method has ended...

众所周知,我们可以通过使用 final 关键字来绕过它.这就是他们在书中所说的,但他们并没有真正解释最后一个关键字的作用是什么......据我所知,在方法局部变量上使用 final 关键字并不能使它存在于堆中......那么该类如何能够访问仍然存在于堆栈中的最终变量,而可能没有更多堆栈???

As we all know, we can bypass this by using the final keyword. This is what they say in the book but they don't really explain what's the effect of that final keyword... As far as i know, using the final keyword on a method local variable doesn't make it live on the heap... So how would the class be able to access a final variable that still lives on the stack while there could be no more stack???

我想内部类中应该有这个最终局部变量的某种副本".既然值不能改变,为什么不复制这个信息......有人可以确认这一点或告诉我我是否遗漏了什么吗?

I guess there should be some kind of "copy" of this final local variable inside the inner class. Since the value can't change, why not duplicating this information... Can someone confirm this or tell me if i'm missing something?

推荐答案

你的直觉是正确的,因为变量是 final,复制它是安全的.当然,对于引用类型,这意味着复制对对象的引用,而不是它所引用的对象.

Your intuition is correct, because the variable is final it is safe to make a copy of it. Of course for reference types this means copying the reference to the object and not the object it refers to.

这篇关于为什么我们在匿名内部类中使用 final 关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆