typestar

Classes in Delphi

A step counter class: one field, one method, and an instance you create and free.

program ClassBasics;
uses SysUtils;
// A class bundles fields with the methods that act on them.
type
  TStepCounter = class
    Steps: Integer;
    procedure Add(N: Integer);
  end;
procedure TStepCounter.Add(N: Integer);
begin
  Steps := Steps + N;  // a method reaches its own fields by name
end;
var Walk: TStepCounter;
begin
  Walk := TStepCounter.Create;  // Create allocates and zeroes the fields
  Walk.Add(1200);
  Walk.Add(850);
  WriteLn(Format('steps today: %d', [Walk.Steps]));
  Walk.Free;                    // one Free for every Create
end.

How it works

  1. TStepCounter = class declares the type and Steps: Integer is the field each instance carries.
  2. procedure TStepCounter.Add is implemented below the declaration and assigns Steps := Steps + N.
  3. TStepCounter.Create allocates the instance and Walk.Free releases it at the end.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
532
Tokens
95
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 81 seconds.

Type this snippet

Step 1 of 3 in Classes, step 19 of 27 in Language basics.

← Previous Next →

Classes in other languages