Static variables(also known as class variables) are shared among all instances of a class.
They are typically used to store information related to the class as a whole, rather than information related to a specific instance of the class.
Static variables are accessible from the class itself without necessarily having to create an instance of the class. They are initialized when the class is first loaded, and do not need to be explicitly initialized in the constructor.
Conventionally, static variables are declared at the top of the class before any other methods or fields. This makes them easily distinguishable from other variables.
Example of a static variable
Consider if we want to create a class that represents a citizen of a particular country, say India. Each objects of such a class can share the variable country. As shown below.
As shown above, to access static variables from outside the class, we use the class itself or an object of the class.
Accessing static variables within the class
We can also access the variables within the class at definition. However, how the variable behaves depends largely on where it is being accessed from.
If we access a static variable from an instance method, any modifications done will only be relevant to the object doing the modification.
On the other hand, if static variables are modified from a class method, the change takes effect in the whole class.
Consider the following example:
Static variables should be used with caution, since they are global state that is shared across all instances of a class. As you have seen above, they behaves differently depending on where they are being accessed/modified.
Understanding how the various methods work can be crucial in avoiding the pitfall of having static variables modified in a way that can lead to unexpected results. Visit the article on Instance, Class and Static methods to see how each of these methods works.