Difference between private static final and private final for the use of immutability

3

An attribute when declared with the static modifier has the characteristic of "propagating its value" for all instances of the class to which it belongs, ie its value will be the same for all instances. Because of this feature these attributes are named class variables. These have their value stored in a memory fixed address . Here's an example:

class Foo {
    public static int count = 0 ;
    Foo() { 
        ++count;
    }
}

Another use for the static modifier is when we want to make an attribute immutable, 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 statements we achieve the same goal, that of making the value of an attribute immutable. Given this, what is the real advantage in using the static modifier in creating immutable variables? Is there any real gain related to performance?

    
asked by anonymous 22.01.2015 / 21:13

2 answers

7

There are some false premises in your question:

  

"In both the static and final statements) we achieve the same goal of making the value of an attribute immutable."

The goal of static is not to implement immutability but rather to declare the member (method, "field", "property", "attribute" ...) in a class instead of publishing in an object (an instance of the class).

You may have confused static with immutable when you realize that once you assign a value to a static member, the reference will remain throughout the application lifecycle - the referenced object will never will be collected by the garbage collector while the application is running.

But this static member is not immutable, since at any moment you can assign another value to it (change its reference to that of another object) or even change the state of the object it references.

The final keyword yes, this helps to implement immutable objects since you can only assign value to the "end" member once, and since the compiler requires that this value be already assigned in the class constructor (if it has not already been assigned in the static member's own declaration).

So, answer the questions directly:

23.01.2015 / 14:52
0

When not using static will have the variable created for each instance of the object, already using the static it will be created only once (it will be of the class and not of the instance). How much this will impact your system depends on many other factors.

    
06.02.2017 / 13:06