Skip to main content
3 of 4
added 345 characters in body
Basile Starynkevitch
  • 32.7k
  • 6
  • 87
  • 131

It is explained here (with an example Bicycle class with class variable numberOfBicycles and instance variables cadence, speed, gear & id):

Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.

A class variable (declared static) is a location common to all instances.

In the example, numberOfBicycles is a class variable (since it is declared static). There is only one such variable (i.e. location) common to all instances and to the class. So if you modify numberOfBicycles in one method, other methods would see the new value (even for different Bicycle objects)

In contrast gear & id are instance variables (because their declaration has no static modifier). Every Bicycle object has its own one. If you modify gear for some Bicycle a, and if b is another instance, modifying a.gear has no effect on b.gear

Each Java object is a distinct memory zone with some meta data (e.g. some reference to its class) and its own instance variables (perhaps inherited from a superclass). But the class variables are common to the class.

See also Object (computer science) & Instance variable wikipages.

Basile Starynkevitch
  • 32.7k
  • 6
  • 87
  • 131