开发者

Can I make a variable final after it has been declared?

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 pre开发者_开发技巧vent 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.


When a variable is final, it absolutely MUST be declared in the constructor, whether in the constructor or when you declare it. So worry not, you can create a final variable for your object, and then if you don't immediately set its value when you declare it, then you'll have to set its value in the constructor. So, technically speaking, both these codes are correct :

public class BankAccount {

    private final int acctNumber;

    public BankAccount(int acctNumber) {
        this.acctNumber = acctNumber;
    }

}
public class BankAccount {

    private final int acctNumber = 12;

    public BankAccount(int acctNumber) {
    }

}


You can do this by doing something like private static final String accNumber = askAccNumber(); And then declare a function:

private static final String askAccNumber (){ //however you want to input your number }

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜