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
finale.g. the following is legal:In fact if a field is marked as
finalbut 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.