5.3 Class or Static fields

An object can contain class or static fields: these fields are global to the object type, and act like global variables, but are known only in the scope of the object. The difference between static and class variables is purely the mode in which they work: The static keyword will always work, the class keyword will need {$MODE DELPHI}.

They can be referenced from within the objects methods, but can also be referenced from outside the object by providing the fully qualified name.

For instance, the output of the following program:

{$mode delphi}  
{$static on}  
type  
  cl=object  
    l : longint; static;  
    class var v : integer;  
  end;  
 
var  
  cl1,cl2 : cl;  
 
begin  
  Writeln(’Static’);  
  cl1.l:=2;  
  writeln(cl2.l);  
  cl2.l:=3;  
  writeln(cl1.l);  
  Writeln(cl.l);  
  Writeln(’Class’);  
  cl1.v:=4;  
  writeln(cl2.v);  
  cl2.v:=5;  
  writeln(cl1.v);  
  Writeln(cl.v);  
end.

will be the following

Static  
2  
3  
3  
Class  
4  
5  
5

Note that the last line of code references the object type itself (cl), and not an instance of the object (cl1 or cl2).