Initialize a static final field in the constructor

A constructor will be called each time an instance of the class is created. Thus, the above code means that the value of x will be re-initialized each time an instance is created. But because the variable is declared final (and static), you can only do this

class A {    
    private static final int x;

    static {
        x = 5;
    }
}

But, if you remove static, you are allowed to do this:

class A {    
    private final int x;

    public A() {
        x = 5;
    }
}

OR this:

class A {    
    private final int x;

    {
        x = 5;
    }
}

Leave a Comment