Cardelco
Cardelco

Reputation: 57

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

Upvotes: 1

Views: 75

Answers (3)

lutzh
lutzh

Reputation: 4965

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.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533500

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.

Upvotes: 0

RamonBoza
RamonBoza

Reputation: 9038

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.

Upvotes: 5

Related Questions