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 two 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.
Note that a class variable is tied to a specific class. Descendent classes will refer to the same instance, unless the variable is redeclared. The following program demonstrates this:
The output of this program is:
Because it is tied to a class, it can be overridden in delphi mode:
It will print the following:
However, in OBJFPC mode it will not compile, and will give a duplicate identifier error.