Similar to objects, a class can contain static fields or class variables: these fields or variables are global to the class, and act like global variables, but are known only as part of the class. They can be referenced from within the classes’ methods, but can also be referenced from outside the class by providing the fully qualified name.
Again, there are 2 ways to define class variables. The first one is equivalent to the way it is done in objects, using a static modifier:
For instance, the output of the following program is the same as the output for the version using an object:
The output of this will be the following:
Note that the last line of code references the class type itself (cl), and not an instance of the class (cl1 or cl2).
In addition to the static field approach, in classes, a Class Var can be used. Similar to the way a field can be defined in a variable block, a class variable can be declared in a class var block:
This definition is equivalent to the previous one.