Search code examples
javastatic-membersclass-variables

How is the value of a static / class variable passed around?


A static / class variable is defined in a type / class and is said to associate with the type / class that it is defined in and is independent of an instances of the type / class. There is exactly one static / class variable in the type / class and is best used for constant like properties, whose value would be common amongst any instances of the class. The state of a static / class variable is always exists in the class and therefore there is only one variable at any moment in the class and the keyword static is used to define this nature of the variable. The static / class variable in best practice is to be initialized once and this is ensured using the keyword final. A final static variable is to be initialized with an immutable collection as in a new String() or new Integer();

Now my question is how is the value from the static variable used? And what is the use of this variable called? E.g does it copy it's value from the class that it is contained in or is it an explicit reference to the variable in the class?

e.g

class GenericType {
    private final static String commonValue = new String("foobar");
} 
class AnotherGenericType {
    public static void main(String[] args) {
        System.out.println(GenericType.commonValue); //Displays foobar in the console.

    }
}

Solution

  • There is space specifically allocated for the storage of static variables. This is specified in the JLS, 8.3.1.1, which states

    If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized.

    It's worth noting that these variables aren't open for garbage collected until the class is unloaded (which doesn't usually happen often), which is a potential for unintended memory references being held.

    Accessing static members could possibly be referred to as 'static access' (I've heard it used before) but generally it doesn't have its own term.