java 我可以在声明变量后将其设为 final 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4189045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I make a variable final after it has been declared?
提问by Matt
I'm making a banking model, and an Account class has an accountNumber field. The account number should never change, but I cannot set the field as final because this will prevent the constructor from setting it.
我正在制作一个银行模型,一个 Account 类有一个 accountNumber 字段。帐号不应更改,但我不能将该字段设置为 final,因为这将阻止构造函数设置它。
If it's not possible to do this, it doesn't matter. It's just for a CS assignment so I want to make sure I'm doing it the best way I can.
如果无法做到这一点,也没关系。这只是一个 CS 任务,所以我想确保我以最好的方式做这件事。
Would the best implementation be to just make the field and its setter method private?
最好的实现是将字段及其设置方法设为私有吗?
回答by mikej
The constructor canset it if it is marked as final
e.g. the following is legal:
如果标记为例如以下是合法的,则构造函数可以设置它final
:
public class BankAccount {
private final int accountNumber;
public BankAccount(int accountNumber) {
this.accountNumber = accountNumber;
}
}
In fact if a field is marked as final
but not initialised in its declaration then it must be set in all constructors.
事实上,如果一个字段final
在其声明中被标记为但未初始化,那么它必须在所有构造函数中设置。
If you do not put a public setter on the class then the account number can't be changed from outside the class but marking it as final will also prevent it (accidentally) being changed by any methods inside the class.
如果您没有在类上放置公共设置器,则无法从类外部更改帐号,但将其标记为 final 也将防止它(意外地)被类内的任何方法更改。
回答by Pablo Fernandez
If a variable is final
it can (and must) be initialized in the constructor.
如果一个变量是final
它可以(并且必须)在构造函数中初始化。