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

Asked

Viewed 15,702 times

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?

  • 4

    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 have final 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.

  • @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.

  • The question should be related to immutability. You’re right.

  • 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.

  • 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.

Show 1 more comment

3 answers

8

There are some false premises in your question:

"In both the instructions [Static and final] we achieve the same goal, that of making the value of an unchanging attribute."

The objective 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 knowledge that once assigned a value to a static member, the reference will remain throughout the application lifecycle - the referenced object will never be collected by the Garbage Collector while the app is running.

But this static member is not immutable, since at any time 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 keyword final yes, this helping to implement immutable objects since you can only assign value to the "final" member once, and since the compiler requires this value to be assigned already in the class constructor (if it has not already been assigned in the static member’s own declaration).

So, by directly answering the questions:

  • "What is the real advantage of using the Static modifier in creating immutable variables?" - Answer: none.

  • "Is there any real gain related to performance?" - Answer: no.

  • "Difference between private final and private final Static for the use of immutability." - Answer: no difference regarding the immutability of the variable.

  • Caffé, I think I was misunderstood. In the two examples I gave, immutability occurs, precisely because of the existence of the final modifier in the instructions. In both, the attempt to change the value of the WHEELS variable will return the error "cannot assign a value to final variable PORTS" by the compiler.

  • 1

    @Geisonsantos I edited the answer trying to add direct answers to your questions.

0

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

0

The difference between Static and final is as follows: private example Static final int A = 10; private Static int B = 15;

      Suponha que a classe que você declarou essas variáveis chama-se (Test)
      ao criar um objeto a partir dessa classe sua variável do tipo static final
      não pode ser alterada o valor por exemplo você não pode fazer isso 
      Test test = new Test(); 
      test.setA(20); Você não consegue mudar o valor da variável.
       
      Já na variável somente static você pode mudar o valor
      Exemplo Test test = new Test();
      test.setB(20); Você consegue altear o valor da variável
      Isso é possível porém se você instanciar outro objeto com outro valor 
      por exemplo Test test2 = new Test();
      test2.setB(30);
      vai prevalecer o valor do ultimo objeto instanciado.
      e test.setB(20); deixa de existir.
      você não pode ter mais de um objeto com valores diferente quando é do 
      tipo statico.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.