Properties, Visibility and Class Members

16.1 Visibility Specifiers

strict private Only the class itself The class and the same unit strict protected The class and descendants Descendants and the same unit

Public + RTTI for the Object Inspector/streaming (components) Legacy OLE automation

Prefer strict private / strict protected for real encapsulation (plain private is unit-wide).

16.2 Properties

Property specifiers: read, write, stored, default, nodefault, index (shared getter with an index), implements (interface delegation).

type
  TPerson = class
  strict private
    FName: string;
    FAge: Integer;
    FPhones: TStringList;
    procedure SetAge(const Value: Integer);
    function GetIsAdult: Boolean;
    function GetPhone(Index: Integer): string;
    procedure SetPhone(Index: Integer; const Value: string);
  public
    constructor Create;
    destructor Destroy; override;
    property Name: string read FName write FName;                 // direct field access
    property Age: Integer read FAge write SetAge default 0;       // setter with validation
    property IsAdult: Boolean read GetIsAdult;                    // read-only computed
    property Phones[Index: Integer]: string read GetPhone write SetPhone; default;   // indexed default property
  end;

procedure TPerson.SetAge(const Value: Integer);
begin
  if (Value < 0) or (Value > 150) then
    raise EArgumentOutOfRangeException.Create('Invalid age');
  FAge := Value;
end;
// usage: P.Age := 30; P[0] := '98765';  (default property)

16.3 Class (Static) Members

Class methods can be virtual (class function Create...: TMyClass; virtual;), which is useful with class references (metaclasses).

type
  TCounter = class
  private
    class var FInstances: Integer;               // shared by all instances
  public
    class constructor Create;                    // runs once before first use
    class destructor Destroy;
    constructor Create;
    class function Instances: Integer; static;   // static: no Self
    class procedure Reset;                       // class method: Self = class reference
    class property Count: Integer read FInstances;
  end;

16.4 Class References (Metaclasses)

type
  TShapeClass = class of TShape;

function CreateShape(AClass: TShapeClass): TShape;
begin
  Result := AClass.Create;        // virtual constructor: creates the right descendant
end;

var S := CreateShape(TCircle);
// Used by the VCL: Application.CreateForm(TForm1, Form1); RegisterClass/FindClass

16.5 Nested Types and Constants

type
  TOrder = class
  public type
    TStatus = (stNew, stPaid, stShipped);
  public const
    MaxLines = 100;
  private
    FStatus: TStatus;
  end;
var St: TOrder.TStatus;