Search code examples
javafinalstatic-variables

When is it better to use static variable?


I am wondering why sometimes I see code with static variable? When is it better to use static variable instead of "normal" variable? If its value do not change from an istance to another, is it not better to use final variable?


Solution

  • The point in using static variables is not the same as final ones.

    Final-declared variables (static or not) cannot be modified. They are often used as "reference values" or constants.

    Static-variables (and methods) are therefore needed as "shared content". For instance, say each person in the office likes to drink coffee. Are we better of with everyone bringing his own coffee machine ? Or are we better sharing one such machine for the entire office ?

    Obviously you want to chose the shared option. In a programming idiom, this would translate to having a static variable in the Office class representing the unique CoffeeMachine.

    Off-topic but surely you wouldn't want to make this coffee machine final. What if someone breaks it ? You would need to replace it, and thus change the variable.