Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize final variable before constructor in Java

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 name";

then I cannot use it in the constructor. Java first runs the constructor and then the fields. Is there a solution that allows me to access the final field in the constructor?

like image 269
Tobias Avatar asked Mar 24 '09 14:03

Tobias


3 Answers

I do not really understand your question. That

public class Test3 {
    private final String test = "test123";

    public Test3() {
        System.out.println("Test = "+test);
    }

    public static void main(String[] args) {
        Test3 t = new Test3();
    }
}

executes as follows:

$ javac Test3.java && java Test3
Test = test123
like image 140
Johannes Weiss Avatar answered Nov 19 '22 08:11

Johannes Weiss


Do the initialization in the constructor, e.g.,

private final String name;
private YourObj() {
    name = "a name";
}

Of course, if you actually know the value at variable declaration time, it makes more sense to make it a constant, e.g.,

private static final String NAME = "a name";
like image 32
Hank Gay Avatar answered Nov 19 '22 08:11

Hank Gay


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.

like image 5
Steve Gelman Avatar answered Nov 19 '22 09:11

Steve Gelman