I was wondering, if I have this field in my class : private final int foo = ...
, should I put it in static private static final int foo = ...
? Beca
If every instance of your class should have the same immutable value for foo, then you should make foo final and static. If each instance of your class can have a different (but still immutable) value for foo, then the value should just be final.
However, if every instance of your class should have the same immutable value for foo, then it is a really a constant. By convention, that is typically coded as follows:
private static final int FOO = ...
Note the caps to denote a constant...
There is a big difference between the two non-access modifiers.
final
means your variable can be assigned a value once. static
sets its scope to pertain to the class (rather than an instance or a local context). There is no reason why they should go together unless by design.
A static final
variable is de facto a constant.
For instance, fields declared in interface
s are implicitly public
, static
and final
.
Amongst the usage examples for final
, non static
fields you can find:
if you initiate its value in the constructor
then it should not be static
like
private final int foo;
public MyClass(int m){
foo=m;
}
because its value depends on entry value.
but if you initiate its value inline like
private final int foo = 100;
then its preferred to be static
to have just one instance of it, since the final
field will be created on each instance of class; but static
will be created once.
It is a constant and you will not want to have one copy of the variable for each instance of the class,so make it static. Also, if you want to use them from a static method, make it static.
Static variables are those variables which are common for all the instances of a class.If one instance changes it, then value of static variable would be updated for all other instances.
If you do not want this behavior, keep it non-static.
A final member can still be set by the constructor: therefore, if each instance of your class can set foo in the constructor and this value should pertain only to that instance, it should only be final, NOT static.
If however, foo is only set at declaration time, it might mean that this is a common value for all instances and you would win a little memory by declaring it static also. Beware though that if foo was not a primitive but a reference member, final only means that the reference can't change, not the content of the object, therefore a final and non static member that is a reference should not automatically be static. You could want one immutable reference per instance of your class, with different object state.