Skip to content
Classes
step 1/5

Reading — step 1 of 5

Learn

~1 min readObject Pascal Classes

Modern Pascal (Object Pascal / FreePascal) supports full OOP with classes, inheritance, virtual methods, interfaces.

program demo;

type
    TPerson = class
    private
        FName: string;
        FAge: integer;
    public
        constructor Create(const AName: string; AAge: integer);
        function Greeting: string;
        property Name: string read FName write FName;
        property Age: integer read FAge write FAge;
    end;

constructor TPerson.Create(const AName: string; AAge: integer);
begin
    FName := AName;
    FAge := AAge;
end;

function TPerson.Greeting: string;
begin
    Result := 'Hi, I''m ' + FName;
end;

var
    p: TPerson;
begin
    p := TPerson.Create('Ada', 36);
    try
        WriteLn(p.Greeting);
        WriteLn(p.Name, ' is ', p.Age);
    finally
        p.Free;
    end;
end.

Key conventions:

  • Class names start with T (Type)
  • Field names start with F (Field) — usually private
  • Use property to expose with getter/setter — clean syntax for callers
  • Always Free instances in finally (manual memory)

Inheritance:

type
    TAnimal = class
    public
        function Sound: string; virtual;
    end;

    TDog = class(TAnimal)
    public
        function Sound: string; override;
    end;

function TAnimal.Sound: string;
begin
    Result := 'generic';
end;

function TDog.Sound: string;
begin
    Result := 'woof';
end;

virtual declares the parent's method as overridable. override matches it. Without virtual/override, the method is statically dispatched.

abstract methods — declared but not implemented:

TShape = class
public
    function Area: real; virtual; abstract;
end;

Must be overridden in concrete subclasses.

Visibility:

  • private — within unit
  • protected — descendants
  • public — anyone
  • published — public + RTTI for runtime introspection (Delphi heritage)

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…