Fields This topic describes the syntax of class data fields declarations.
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. All field declarations must occur
before any property or method declarations. For example, the following declaration creates a class called
TNumber
whose only member, other than the methods is inherits from TObject, is an integer field called
Int
.
type TNumber = class
Int: Integer;
end;
Fields are statically bound; that is, references to them are fixed at compile time. To see what this means, consider
the following code.
type
TAncestor = class
Value: Integer;
end;
TDescendant = class(TAncestor)
Value: string; // hides the inherited Value field
end;
var
MyObject: TAncestor;
begin
MyObject := TDescendant.Create;
MyObject.Value := 'Hello!' // error
(MyObject as TDescendant).Value := 'Hello!' // works!
end;
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.
Constants, and typed constant declarations 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).