3
An attribute when declared with the modifier Static has the characteristic of "propagating its value" by all instances of the class to which it belongs, that is, its value will be the same for all instances. Due to this feature these attributes are named after class variables. They have their value stored in a fixed address memory. Here is an example:
class Foo {
public static int count = 0 ;
Foo() {
++count;
}
}
Another use for the Static modifier is when we want to make an immutable attribute unalterable, achieved from the addition of the final modifier, as in the following example:
class Carro {
private static final int RODAS = 4;
...
}
The same result is when we declare the attribute without the Static modifier, only with the final modifier.
class Carro {
private final int RODAS = 4;
...
}
In both instructions we achieve the same goal, that of making the value of an attribute immutable. Given this, what is the real advantage of using the Static modifier in creating immutable variables? Is there any real gain related to performance?
I think it’s been answered here http://answall.com/a/17136/101 Or not?
– Maniero
Just to put something specific: immutability and range of a variable are orthogonal things.
static
defines that it will exist for all instances of the class. Point. If you havefinal
or is not irrelevant to this issue.final
defines that the value cannot be changed. One does not depend on or relates to the other.– Maniero
@Bigown, you’re right, answer is on the link you went through. But the answer you were looking for is not the one marked as correct in this one, but the one you posted in it.
– Geison Santos
The question should be related to immutability. You’re right.
– Geison Santos
My interest with the post was to know the difference between the two approaches to reach immutability; with the use of the modifier Static and without its use, through the final modifier.
– Geison Santos
I also thought mine answered better :) But acceptance is a criterion of each and the acceptance was more complete in general terms. As no one answered yet, I think it would be okay to change the question. But I don’t know if there really would be any difference. The
static
has not none relation to immutability.– Maniero