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.
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.
Would the best implementation be to just make the field and its setter method private?
The constructor can set it if it is marked as final
e.g. the following is legal:
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.
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.
If a variable is final
it can (and must) be initialized in the constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With