Search code examples
javastaticfinal

Use of final instance variables which value is known at compilation time


Is there any case when it makes sense to use a final instance variable instead of a static final instance variable, when you already know its value at compilation time at it's the same for all instances?

I mean, despite this initialization is syntactically valid:

class Test {

    final int size = 3;

    ...
}

It will create one copy per instance, so the question is if there is any case when it would make sense to do that instead of:

class Test {

    static final int size = 3;

    ...
}

And make one copy for all instances.

Thank you


Solution

  • The purpose of final but non-static variables is to have an object-wide constant. It should be initialized in the constructor.

    class A {
        final int a;
    
        A(int a) {
            this.a = a;
        }
    }
    

    If you initialize the variable in declaration, it is best practice to use static keyword.