将实例变量作为最终的点? [英] point of having an instance variable as final?

查看:85
本文介绍了将实例变量作为最终的点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将实例变量作为final是什么意思?

what is the point of having an instance variable as final?

将变量设置为静态最终变量不是更好吗?

isn´t it better to have that variable set as a static final variable then?

因为如果它不能被任何对象改变,那么它与类(静态)变量相同,对吗?

cause if it can't be changed by any of the objects, then it's the same as a class (static) variable, right?

推荐答案

不。 static 表示它在所有类的实例中都是相同的。 final 表示在初始分配后无法分配。因此,对于非静态最终变量,两个实例可能具有不同的值。

Nope. static means it's the same across all instances of the class. final means it's not assignable after its initial assignment. So two instances could have different values for a non-static final variable.

您可能希望将变量设为final的原因有很多;其中最好的是清晰度。如果我读了一个方法并注意到foo是最终的,我不必担心它在下面的位置 - 因为它不是;它不能。我可以对代码进行更多更改,而最终变量的关注度较低(我是否在bar之前或之后更改了foo的值,这是否重要?)因为我知道某些变量不会发生变化。它还将我的注意力集中在 可能发生变化的变量上 - 而且它们是值得更多关注的变量。

There are many reasons you might want to make a variable final; one of the best is clarity. If I read a method and notice that the foo is final, I don't have to worry about where it's changing down below - because it isn't; it can't. I can make more changes to code with final variables with less concern ("did I change the value of foo before or after bar, and does it matter?") because I know that some variables aren't subject to change. It also focuses my attention on the variables that are subject to change - and they're the ones that deserve more attention.

这篇关于将实例变量作为最终的点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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