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
TStepCounter = classdeclares the type andSteps: Integeris the field each instance carries.procedure TStepCounter.Addis implemented below the declaration and assignsSteps := Steps + N.TStepCounter.Createallocates the instance andWalk.Freereleases it at the end.
Keywords and builtins used here
AddFormatIntegerTStepCounterWriteLnbeginclassendprocedureprogramtypeusesvar
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.
Step 1 of 3 in Classes, step 19 of 27 in Language basics.