Initialize final variable before constructor in Java

后端 未结 9 1719
旧时难觅i
旧时难觅i 2020-12-03 09:00

Is there a solution to use a final variable in a Java constructor? The problem is that if I initialize a final field like:

private final String name = \"a na         


        
9条回答
  •  既然无缘
    2020-12-03 09:30

    We're getting away from the question.

    Yes, you can use a private final variable. For example:

    public class Account {
        private final String accountNumber;
        private final String routingNumber;
    
        public Account(String accountNumber, String routingNumber) {
            this.accountNumber = accountNumber;
            this.routingNumber = routingNumber;
        }
    }
    

    What this means is that the Account class has a dependency on the two Strings, account and routing numbers. The values of these class attributes MUST be set when the Account class is constructed, and these number cannot be changed without creating a new class.

    The 'final' modifier here makes the attributes immutable.

提交回复
热议问题