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

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

问题描述

我正在准备S(O)CJP,塞拉利昂&贝茨预定。

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猜猜在内部类中应该有这种最终局部变量的某种复制。由于价值无法改变,为什么不重复这些信息...
有人可以确认这个或告诉我我是否遗漏了什么?

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?

推荐答案

你的直觉是正确的,因为变量是最终的,所以制作它的副本是安全的。当然对于引用类型,这意味着复制对象的引用而不是它引用的对象。

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天全站免登陆