Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 709
Matt Avatar asked Nov 15 '10 21:11

Matt


2 Answers

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.

like image 83
mikej Avatar answered Oct 11 '22 08:10

mikej


If a variable is final it can (and must) be initialized in the constructor.

like image 42
Pablo Fernandez Avatar answered Oct 11 '22 09:10

Pablo Fernandez