Object-Oriented Programming (OOP) Grade 12

OOP lets you model real-world things as objects in code. Think of a class as a blueprint (like architectural plans for a house) and an object as the actual building made from that plan. One blueprint, many buildings — one class, many objects.

T2Term 2 · Classes, Objects & Core OOP Concepts
ANALOGY — OOP is a taxi

Every part of OOP maps neatly onto a taxi:

  • Class = the design of a taxi — the plans that say what every taxi has and can do. There is only one design.
  • Object (instance) = one actual taxi on the road, e.g. the one with registration CA 123‑456. From the one design you can build many taxis.
  • Attributes = what a taxi has: make, registration, colour, number of seats, fuel level, current speed.
  • Methods = what a taxi does: StartEngine, Drive, Stop, PickUp, DropOff, Hoot.
  • Constructor (Create) = building a brand-new taxi at the factory and giving it its starting details (make, registration).
  • Encapsulation = you drive with the steering wheel and pedals (public methods); you never reach into the engine (private attributes). The engine is hidden under the bonnet — and that keeps it safe.
  • Accessor (getter) = the fuel gauge lets you read the fuel level without touching the tank. Mutator (setter) = filling up at the petrol station changes the fuel level in a controlled way.
  • Inheritance = a taxi is‑a vehicle: it inherits "drive" and "stop" from a general TVehicle, then adds its own meter and passenger seats.
  • Polymorphism = tell any vehicle to Hoot and each does it its own way — a sedan taxi beeps, a minibus blares.
TCat class structure in Delphi's code view
TCat class structure in Delphi's code view

Core OOP Concepts

TermDefinition
ClassA blueprint or template that describes what an object looks like and can do
ObjectA specific instance of a class (like one particular cat — Whiskers)
AttributeA variable that stores data about the object (e.g. fName, fAge)
MethodA procedure or function that belongs to the class (e.g. GetName, SetAge)
ConstructorSpecial method Create that creates an instance and sets initial values
EncapsulationHiding private data inside a class; only accessible through public methods
InheritanceA new class inherits all attributes and methods of an existing (parent) class
PolymorphismThe same method name behaves differently in different classes
You already use OOP!

In Delphi, every component is an object. TButton is a class; btnOK is an object. TForm is a class; Form1 is an object. OOP lets you create your own custom classes.

One Class, Many Objects

A class is defined once. You can create as many objects (instances) from it as you need — each with its own data.

TCat (CLASS) Blueprint / Template - fName : String - fAge : Integer + Create(sName, iAge) + GetName : String + ToString : String Create objCat1 (Object) fName = 'Whiskers' fAge = 3 objCat1 := TCat.Create('Whiskers', 3); objCat2 (Object) fName = 'Felix' fAge = 5 objCat2 := TCat.Create('Felix', 5); objCat3 (Object) fName = 'Shadow' fAge = 1 objCat3 := TCat.Create('Shadow', 1); Same class TCat — three different objects with different data. The class defines the structure; objects hold the actual values.

UML Class Diagram

Before coding a class, design it using a UML (Unified Modeling Language) diagram — a rectangle divided into 3 sections.

TCat Private attributes (data) - fName : String - fAge : Integer - fWeight : Real Public methods (behaviour) + Create(sName: String; iAge: Integer) + GetName : String + SetName(sName: String) + ToString : String - = private (hidden) + = public (accessible)

Encapsulation

Keep attributes private — hidden from the outside world. Only expose them through controlled public methods (getters and setters). This protects data from accidental or invalid changes.

PUBLIC — accessible from outside the class GetName : String SetName(s: String) GetAge : Integer ToString : String PRIVATE — hidden inside class - fName : String - fAge : Integer - fWeight : Real
Delphi — encapsulation
private
  fName: string;         // hidden from outside — direct access blocked
public
  procedure SetName(s: string);  // controlled write access (can include validation)
  function  GetName: string;     // controlled read access

Inheritance

A child class inherits all attributes and methods from a parent class, and can add or override its own. This avoids repeating code.

TAnimal - fName : String + Speak (virtual) is-a is-a TDog inherits fName from TAnimal + Speak (override) → 'Woof!' TCat inherits fName from TAnimal + Speak (override) → 'Meow!'
Delphi — inheritance
type
  TAnimal = class
    procedure Speak; virtual;  // can be overridden in child classes
  end;

  TDog = class(TAnimal)       // inherits everything from TAnimal
    procedure Speak; override;  // replaces TAnimal.Speak
  end;

  TCat = class(TAnimal)
    procedure Speak; override;
  end;

Polymorphism

The same method name (Speak) behaves differently depending on the type of object. "Many forms" — poly = many, morph = form.

ObjectMethod CalledResult
objAnimal.SpeakTAnimal.Speak'Animal sound...'
objDog.SpeakTDog.Speak (overridden)'Woof!'
objCat.SpeakTCat.Speak (overridden)'Meow!'
Delphi — polymorphism
procedure TAnimal.Speak;
begin
  ShowMessage('Animal sound...');
end;

procedure TDog.Speak;
begin
  ShowMessage('Woof!');
end;

procedure TCat.Speak;
begin
  ShowMessage('Meow!');
end;

Types of Methods

Method TypeKeywordDescription
ConstructorconstructorCreates the object and sets initial attribute values. Called on the class name: TCat.Create(...)
Accessor (getter)functionReturns the value of a private attribute. Read-only access.
Mutator (setter)procedureUpdates the value of a private attribute. Can include validation.
ToStringfunctionReturns a string representation of the object's state — used for display.
AuxiliaryprivateInternal helper methods used by other methods, not accessible from outside.
What does an auxiliary method actually do?

An auxiliary method is a private helper that does one small job for an accessor or mutator, so that method doesn't get cluttered with extra logic. It takes the data it's given, processes it, and returns the result — it never changes the object's attributes itself. Using auxiliary methods reduces complexity inside a class and keeps each method focused on a single task.

Delphi — an auxiliary method used by ToString
private
  function FormatWeight(rWeight: real): string;  // auxiliary — helper only, not called from outside the class
public
  function ToString: string;

// ...
function TCat.FormatWeight(rWeight: real): string;
begin
  Result := FloatToStrF(rWeight, ffFixed, 4, 1) + 'kg';  // just formats — doesn't change fWeight
end;

function TCat.ToString: string;
begin
  Result := fName + ', ' + FormatWeight(fWeight);  // ToString calls the auxiliary method
end;

Common Exam Traps

Trap — function vs procedure

A function returns a value and can be used inside an expression. A procedure performs an action and returns nothing. If the question says a routine "displays" something on screen, that's a procedure — displaying is not the same as returning.

Trap — value vs reference parameters

A value parameter passes a copy — changes made to it disappear when the routine ends. A reference parameter (var in Delphi) passes the actual variable — changes persist in the calling code. Whenever a question says a routine must change two values and return them to the caller, you need reference parameters.

Trap — syntax vs logic vs runtime errors

A syntax error breaks the rules of the language and won't compile. A logic error compiles and runs, but produces the wrong answer — the compiler can never find this one for you, which is exactly why trace tables exist. A runtime error crashes the program while it's running, e.g. division by zero or an array index out of bounds.

How to Create a Class in Delphi

  1. Go to File → New → Unit – Delphi to create a new blank unit.
  2. Save it in the same folder as your project (e.g. UCar.pas).
  3. Type the class structure in the interface section (see template below).
  4. Press Ctrl+Shift+C — Delphi auto-generates the method bodies in the implementation section.
  5. Fill in the code inside each method body.
  6. In your main form unit, add the unit name to the uses clause (e.g. uses ..., UCar;).
Ctrl+Shift+C is your best friend!

After writing the class declaration in the interface section, press Ctrl+Shift+C and Delphi automatically creates all the empty method implementations in the implementation section. You just fill in the code.

Complete Class Example — TCat

Delphi — TCat unit (UCat.pas)
unit UCat;

interface

type
  TCat = class
  private
    fName   : string;
    fAge    : integer;
    fWeight : real;
  public
    constructor Create(sName: string; iAge: integer; rWeight: real);
    function    GetName   : string;
    function    GetAge    : integer;
    function    GetWeight : real;
    procedure   SetName(sNew: string);
    function    ToString  : string;
  end;

implementation

constructor TCat.Create(sName: string; iAge: integer; rWeight: real);
begin
  fName   := sName;
  fAge    := iAge;
  fWeight := rWeight;
end;

function TCat.GetName : string;
begin
  Result := fName;
end;

function TCat.GetAge : integer;
begin
  Result := fAge;
end;

function TCat.GetWeight : real;
begin
  Result := fWeight;
end;

procedure TCat.SetName(sNew: string);
begin
  fName := sNew;
end;

function TCat.ToString : string;
begin
  Result := fName + ', Age: ' + IntToStr(fAge)
          + ', Weight: ' + FloatToStr(fWeight) + 'kg';
end;

end.

Parameterised vs Non-Parameterised Constructors

A class can have more than one constructor. The one shown above — Create(sName: string; iAge: integer; rWeight: real) — is a parameterised constructor: it takes arguments and uses them to set the object's attributes immediately, at the moment the object is created.

A class can also have a non-parameterised constructor — just Create with no arguments — which creates the object with default/empty values instead, to be filled in later using the mutator methods:

Delphi — a non-parameterised constructor for TCat
constructor TCat.Create;
begin
  fName   := '';
  fAge    := 0;
  fWeight := 0;
end;
Parameterised Create(...)Non-parameterised Create
Values setImmediately, from the arguments passed inDefault/empty — must be set afterwards
When you'd use itYou already know the object's details when creating itYou'll fill in the details later, or the user will type them in afterwards
EXAM ANGLE — distinguishing the two constructors

"Distinguish between the parameterised and non-parameterised constructor" wants exactly this — one sets real values straight away from arguments, the other creates an empty object with default values that gets filled in later.

Practice Example — TCar Class

This is the kind of class you will write in a Grade 12 exam. Study the pattern carefully — constructor, accessors, mutator, ToString.

Delphi — UCar.pas (complete working class)
unit UCar;

interface

type
  TCar = class
  private
    fMake  : string;    // e.g. 'Toyota'
    fYear  : integer;   // e.g. 2022
  public
    constructor Create(sMake: string; iYear: integer);
    function    GetMake  : string;
    function    GetYear  : integer;
    procedure   SetMake(sNewMake: string);
    function    ToString : string;
  end;

implementation

constructor TCar.Create(sMake: string; iYear: integer);
begin
  fMake := sMake;
  fYear := iYear;
end;

function TCar.GetMake : string;
begin
  Result := fMake;
end;

function TCar.GetYear : integer;
begin
  Result := fYear;
end;

procedure TCar.SetMake(sNewMake: string);
begin
  fMake := sNewMake;    // could add validation here (e.g. check not empty)
end;

function TCar.ToString : string;
begin
  Result := fMake + ' (' + IntToStr(fYear) + ')';
  // Output example: 'Toyota (2022)'
end;

end.

Using TCar in the Main Form

Delphi — main form unit
// 1. Add UCar to uses clause of the main form
uses
  ..., UCar;

// 2. Declare object variable (global or local)
var
  objCar : TCar;

// 3. Create the object — in a button click or FormCreate
objCar := TCar.Create('Toyota', 2022);

// 4. Read values using accessors
lblMake.Caption := objCar.GetMake;                 // 'Toyota'
lblYear.Caption := IntToStr(objCar.GetYear);       // '2022'
memOut.Lines.Add(objCar.ToString);                 // 'Toyota (2022)'

// 5. Update a value using mutator
objCar.SetMake('Honda');
lblMake.Caption := objCar.GetMake;                 // 'Honda'
Creating an object from the TCat class
Creating an object from the TCat class
Always create before use!

Always call Create before using any other method. The object does not exist until it is created. Also make sure the class unit name is in the uses clause of your main form.

Using a Class in the Main Form

Delphi — main form (TCat example)
uses
  ..., UCat;

var
  objCat : TCat;

// Create the object
objCat := TCat.Create('Whiskers', 3, 4.2);

// Use its accessors
lblName.Caption := objCat.GetName;           // 'Whiskers'
lblAge.Caption  := IntToStr(objCat.GetAge);  // '3'
memOut.Lines.Add(objCat.ToString);           // 'Whiskers, Age: 3, Weight: 4.2kg'

// Update via mutator
objCat.SetName('Felix');
lblName.Caption := objCat.GetName;           // 'Felix'

Worked Example — Methods with Logic (TLibraryBook)

The classes above only copy values in and out. Real tasks ask for methods that build, decide and calculate. We will use a new class, TLibraryBook, to practise each technique. A school library keeps a title, an author, the number of copies, a wear rating from 1 (like new) to 10 (falling apart) and the number of days a book may be borrowed.

Delphi — the class declaration
type
  TLibraryBook = class
  private
    fBookID   : string;
    fTitle    : string;
    fAuthor   : string;
    fCopies   : integer;
    fWear     : integer;     // 1 = like new ... 10 = falling apart
    fLoanDays : integer;     // how many days it may be borrowed
    function GenerateID : string;   // auxiliary: only used inside the class
  public
    constructor Create(sBookID, sTitle, sAuthor: string; iCopies: integer);
    function    GetWear : integer;
    procedure   SetLoanDays(iDays: integer);
    procedure   RecordCheck(sResult: string);
    function    DueDate(dBorrowed: TDate) : TDate;
    function    IsAvailable : boolean;
    function    ToString : string;
  end;

Generating and Returning an ID

An ID is often built from pieces of other attributes. Copy(text, start, count) cuts out part of a string. To get the last two characters, start at Length(text) - 1 and copy 2. Numbers must be converted with IntToStr before they can be joined to text, and UpperCase makes the letters capitals. Here the ID is the first four letters of the title, the last two letters of the author, and the number of copies.

Delphi — a function that builds the ID
function TLibraryBook.GenerateID : string;
begin
  Result := UpperCase(Copy(fTitle, 1, 4) +
                      Copy(fAuthor, Length(fAuthor) - 1, 2)) +
            IntToStr(fCopies);
  // 'Long Walk to Freedom', 'Nelson Mandela', 3  gives  'LONGLA3'
end;

The function only returns the text through Result; it does not store it. Whoever calls it decides what to do with the answer.

A Constructor with Default Values and a Conditional ID

A constructor does not have to take a value for every attribute. Some attributes can simply start with a sensible default. It can also make decisions: below, a book that arrives with the ID 'None' is given a generated ID by calling the auxiliary method; a book that already has an ID keeps it.

Delphi — defaults plus conditional initialisation
constructor TLibraryBook.Create(sBookID, sTitle, sAuthor: string; iCopies: integer);
begin
  fBookID   := sBookID;
  fTitle    := sTitle;
  fAuthor   := sAuthor;
  fCopies   := iCopies;
  fWear     := 2;       // default: a new book is nearly like new
  fLoanDays := 14;      // default loan period

  if fBookID = 'None' then
    fBookID := GenerateID;   // ask the auxiliary method for an ID
end;
Trap — set the attributes before calling GenerateID

GenerateID reads fTitle, fAuthor and fCopies. If you call it before those lines have run, it works with empty values and returns a wrong (or crashing) ID. Do the plain assignments first and the conditional step last.

A Mutator with a Rule

A mutator is not always a one-line assignment. It can change the attribute according to a rule: here a repair reduces the wear by 3 but never below the minimum of 1, and a report of damage sets the wear to the fixed value 10.

Delphi — change an attribute using a rule
procedure TLibraryBook.RecordCheck(sResult: string);
begin
  if sResult = 'Repaired' then
  begin
    fWear := fWear - 3;
    if fWear < 1 then
      fWear := 1;                // never go below the minimum
  end;

  if sResult = 'Damaged' then
    fWear := 10;                 // special case: a fixed value
end;

procedure TLibraryBook.SetLoanDays(iDays: integer);
begin
  fLoanDays := iDays;
end;

function TLibraryBook.GetWear : integer;
begin
  Result := fWear;
end;

A Function That Returns a Date

A TDate is really a number: the count of days since a starting date, so adding a whole number to a date moves it forward by that many days. A method can therefore take a date in, add an attribute, and return the new date. The caller converts the returned date to text with DateToStr to display it.

Delphi — borrowed date + loan days = due date
function TLibraryBook.DueDate(dBorrowed: TDate) : TDate;
begin
  Result := dBorrowed + fLoanDays;
end;

// in the form:
dBorrowed := Date;                                      // today
lblDue.Caption := DateToStr(objBook.DueDate(dBorrowed));

A Boolean Helper Method

A method that answers a yes/no question returns a boolean. Combine the tests with and / or, and put each comparison in its own brackets.

Delphi — two attribute tests in one answer
function TLibraryBook.IsAvailable : boolean;
begin
  Result := (fCopies > 0) and (fWear < 8);   // a copy is left AND it is in fair condition
end;
Why the brackets matter

In Delphi and binds more tightly than > or <. Without the brackets, fCopies > 0 and fWear < 8 is read in the wrong order and will not compile. Bracket every comparison.

ToString with Line Breaks

A ToString that must show one fact per line joins the pieces with the character #13 (a carriage return). In a memo or RichEdit this starts a new line. A Windows line break is really the pair #13#10 (carriage return + line feed); use that pair when the text is going into a single Text property or message box, or when a plain #13 does not give a proper break.

Delphi — a multi-line ToString
function TLibraryBook.ToString : string;
begin
  Result := fTitle + ' [' + fBookID + ']' + #13 +
            'Author: ' + fAuthor + #13 +
            'Copies: ' + IntToStr(fCopies) + #13 +
            'Wear (1-10): ' + IntToStr(fWear) + #13 +
            'Loan period: ' + IntToStr(fLoanDays) + ' days';
end;

Calling the Methods from the Form — Procedure, Accessor, CASE, Mutator

A common pattern in the form is: call a procedure that changes the object, read the new state with an accessor, use that value as the selector of a case statement, and call a mutator in each branch. The ranges in the case use ...

Delphi — apply a check, then set the loan period from the wear
procedure TfrmLibrary.btnCheckClick(Sender: TObject);
begin
  objBook.RecordCheck(edtResult.Text);        // 1. change the wear

  case objBook.GetWear of                   // 2. the accessor result picks the branch
    1..4  : objBook.SetLoanDays(21);        // 3. a mutator in every branch
    5..7  : objBook.SetLoanDays(14);
    8..10 : objBook.SetLoanDays(7);
  end;

  redOut.Lines.Clear;
  redOut.Lines.Add(objBook.ToString);         // 4. show the refreshed object
end;

Object Lifetime in the Form

When the object is created in one button and used in others, the object variable must be declared at form level (not inside one procedure) so every event can see it. Manage its lifetime in three places:

Delphi — create, replace and release an object
var
  objBook : TLibraryBook;          // form level: shared by all the events

procedure TfrmLibrary.FormCreate(Sender: TObject);
begin
  objBook := nil;
end;

procedure TfrmLibrary.btnAddClick(Sender: TObject);
begin
  objBook.Free;                   // release the old book (safe even when it is nil)
  objBook := nil;
  objBook := TLibraryBook.Create('None', edtTitle.Text, edtAuthor.Text, sedCopies.Value);
  redOut.Lines.Add(objBook.ToString);
end;

procedure TfrmLibrary.FormDestroy(Sender: TObject);
begin
  objBook.Free;
  objBook := nil;
end;
Trap — calling a method on an object that does not exist

If the user clicks the check button before any book has been created, objBook is still nil and objBook.RecordCheck(...) raises an access violation. Test with if objBook = nil then ShowMessage('Create a book first') before using it.

Dynamic Components — Creating Controls at Runtime

You already know that every Delphi control is an object of a class (a button is a TButton, a label is a TLabel). Because they are classes, you can create them in code while the program is running using the same Create constructor you use for your own classes — instead of dragging them onto the form at design time.

This is called creating a dynamic component. It is useful when you don't know in advance how many controls you need (e.g. one button per record loaded from a file).

The Four Steps

  1. Create the object from its class, passing the owner (usually the form).
  2. Set the Parent so Delphi knows where to draw it (which form/panel).
  3. Set properties like position, size and caption.
  4. Assign an event handler so it actually does something when clicked.
Delphi — create a button at runtime
var
  btnDynamic : TButton;
begin
  // 1. Create the object (Form1 is the owner – frees it automatically)
  btnDynamic := TButton.Create(Form1);

  // 2. Set the Parent so it appears on the form
  btnDynamic.Parent := Form1;

  // 3. Set properties
  btnDynamic.Left    := 50;
  btnDynamic.Top     := 50;
  btnDynamic.Width   := 100;
  btnDynamic.Height  := 30;
  btnDynamic.Caption := 'Click Me';

  // 4. Assign an event handler (a procedure you wrote)
  btnDynamic.OnClick := btnDynamicClick;
end;

// The handler the button will run when clicked
procedure TForm1.btnDynamicClick(Sender: TObject);
begin
  ShowMessage('Dynamic button clicked!');
end;
Owner vs Parent — what's the difference?

Owner (the argument to Create) is responsible for freeing the component from memory when the form closes. Parent decides where on screen the component is drawn. They are usually the same form, but not always (e.g. Owner = Form, Parent = a Panel on that form).

Avoid memory leaks

If you create a component with Create(nil) (no owner), you must free it yourself with btnDynamic.Free; when you are done, otherwise it stays in memory. Passing the form as the owner lets Delphi clean up for you automatically.

An actual instance created from a class is called a(n):

A class is the blueprint; an object is an actual instance built from it.

Hiding an object's data and exposing it only through methods is:

Encapsulation keeps attributes private and controls access through public methods.

The special method that creates an object and sets its starting values is the:

The constructor (Create) builds the object and initialises its attributes.