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:21

I cannot use it in the constructor, while java first runs the constructor an then the fields...

This is not correct, fields are evaluated first, otherwise you couldn't access any default values of members in your constructors, since they would not be initialized. This does work:

public class A {
    protected int member = 1;
    public A() {
        System.out.println(member);
    }
}

The keyword final merely marks the member constant, it is treated as any other member otherwise.

EDIT: Are you trying to set the value in the constructor? That wouldn't work, since the member is immutable if defined as final.

查看更多
放荡不羁爱自由
3楼-- · 2019-01-12 01:24

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
查看更多
SAY GOODBYE
4楼-- · 2019-01-12 01:25

Marking it static, will allow you to use it in the constructor, but since you made it final, it can not be changed.

private static final String name = "a_name";

is is possible to use a static init block as well.

private static final String name;

static { name = "a_name"; }

If you are trying to modify the value in the constructor, then you can't assign a default value or you have to make it not final.

private String name = "a_name";
Foo( String name )
{
    this.name = name;
}

or

private final String name;

Foo( String name )
{
    if( s == null )
       this.name = "a_name";
    else
       this.name = name;
}
查看更多
登录 后发表回答