Initialize final variable before constructor in Ja

2019-01-12 00:37发布

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?

9条回答
乱世女痞
2楼-- · 2019-01-12 01:02
private static final String name = getName();

where getName() is a static function that gets you the name.

查看更多
小情绪 Triste *
3楼-- · 2019-01-12 01:03

In that case, you might as well make it static, too. And Java convention is to name such constants in ALL_CAPS.

查看更多
Rolldiameter
4楼-- · 2019-01-12 01:04

Another possiblity is to initialize the field in an instance initializer blocK:

public class Foo {
        final String bar;

        {
                System.out.println("initializing bar");
                bar = "created at " + System.currentTimeMillis();
        }

        public Foo() {
                System.out.println("in constructor. bar=" + bar);

        }

        public static void main(String[] args) {
                new Foo();
        }
}
查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-01-12 01:05

In this case, you can mark the field as 'static' also.

查看更多
该账号已被封号
6楼-- · 2019-01-12 01:14

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";
查看更多
三岁会撩人
7楼-- · 2019-01-12 01:15

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.

查看更多
登录 后发表回答