声明最终变量,但稍后设置 [英] Declare final variable, but set later
问题描述
我知道这是一个相当简单的话题,但我真的很想绕过它。
I know this is fairly simple topic, but I really want to wrap my head around it.
这就是我想要做的,但它没有不喜欢最后的修饰符。还有另一种方法可以达到我想要的效果吗?这基本上是我想要确保id在整个活动期间不能改变。
This is what I'm trying to do, but it doesn't like the final modifier. Is there another way to achieve the effect I'm looking for? Which is basically that I want to make sure the id can not change durning the Activities entire life.
private final long mId;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mId = getIntent().getLongExtra(ID_KEY, -1);
}
我应该指出这是Android代码。谢谢你的帮助。我并不担心搞瘾者或者不知所措或任何改变我代码的人。我问的原因是将来证明我的代码将由下一个开发人员接管。我发现这篇文章也有助于解决问题。 Android - 活动构造函数与onCreate
I should point out that this is Android code. Thanks for all the help. I'm not worried about getters or setters or anyone changing my code. The reason I asked was to future proof my code for the next developer to take over. I found this post that also helps shed some light. Android - Activity Constructor vs onCreate
推荐答案
您只能在构造函数或初始值设定项中设置 final
变量。常规方法不能更改声明 final
的变量值。
You can set a final
variable only in a constructor or in an initializer. Regular methods cannot change the value of variables declared final
.
这篇关于声明最终变量,但稍后设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!