Fields (Object Pascal)

About Fields

A field is like a variable that belongs to an object. Fields can be of any type, including class types. (That is, fields can hold object references.) Fields are usually private.

To define a field member of a class, simply declare the field as you would a variable. For example, the following declaration creates a class called TNumber whose only member, other than the methods inherited from System.TObject, is an integer field called Int:

typeTNumber=classvarInt:Integer;end;

The var keyword is optional. However, if it is not used, then all field declarations must occur before any property or method declarations. After any property or method declarations, the var may be used to introduce any additional field declarations.

Fields are statically bound; that is, references to them are fixed at compile time. To see what this means, consider the following code:

Although MyObject holds an instance of TDescendant, it is declared as TAncestor. The compiler therefore interprets MyObject.Value as referring to the (integer) field declared in TAncestor. Both fields, however, exist in the TDescendant object; the inherited Value is hidden by the new one and can be accessed through a typecast.

Declarations of constants and typed constants can appear in classes and non-anonymous records at global scope. Both constants and typed constants can also appear within nested type definitions. Constants and typed constants can appear only within class definitions when the class is defined locally to a procedure (i.e. they cannot appear within records defined within a procedure).

Class Fields

Class fields are data fields in a class that can be accessed without an object reference (unlike the normal "instance fields" which are discussed above). The data stored in a class field are shared by all instances of the class and may be accessed by referring to the class or to a variable that represents an instance of the class.

You can introduce a block of class fields within a class declaration by using the class var block declaration. All fields declared after class var have static storage attributes. A class var block is terminated by the following: