1

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

2
  • Yes, you said it yourself: you would use the first alternative when each instance needs its own size member. What are you asking? Commented Nov 15, 2013 at 14:46
  • I will use the first alternative if the size for each instance would be different, initilizing the size on the constructor but I'm asking if there is any case when It makes sense to initialize a final instance variable when you declare it (that means, you already know that its value is always 3) or in those cases always a static final instance variable is a better approach Commented Nov 15, 2013 at 14:51

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

0

I try to make any method or field which can be static is static. This helps performance but the best reason to do this is to make it clear that the field is the same for all instances.

Comments

0

I don't know if it counts as "makes sense", but I think it would make a difference when you consider serialization, or getting all fields of an instance via reflection.

I imagine something like a server that receives JSON messages from different systems where the size property may have different values, even though all messages from your Java client have size 3. If you want the size included in the message and not have to customize your serialization, declaring it as an (non-static) instance variable might be the easiest way.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.