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.
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
Hootand each does it its own way — a sedan taxi beeps, a minibus blares.
Core OOP Concepts
| Term | Definition |
|---|---|
| Class | A blueprint or template that describes what an object looks like and can do |
| Object | A specific instance of a class (like one particular cat — Whiskers) |
| Attribute | A variable that stores data about the object (e.g. fName, fAge) |
| Method | A procedure or function that belongs to the class (e.g. GetName, SetAge) |
| Constructor | Special method Create that creates an instance and sets initial values |
| Encapsulation | Hiding private data inside a class; only accessible through public methods |
| Inheritance | A new class inherits all attributes and methods of an existing (parent) class |
| Polymorphism | The same method name behaves differently in different classes |
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.
UML Class Diagram
Before coding a class, design it using a UML (Unified Modeling Language) diagram — a rectangle divided into 3 sections.
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.
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 accessInheritance
A child class inherits all attributes and methods from a parent class, and can add or override its own. This avoids repeating code.
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.
| Object | Method Called | Result |
|---|---|---|
objAnimal.Speak | TAnimal.Speak | 'Animal sound...' |
objDog.Speak | TDog.Speak (overridden) | 'Woof!' |
objCat.Speak | TCat.Speak (overridden) | 'Meow!' |
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 Type | Keyword | Description |
|---|---|---|
| Constructor | constructor | Creates the object and sets initial attribute values. Called on the class name: TCat.Create(...) |
| Accessor (getter) | function | Returns the value of a private attribute. Read-only access. |
| Mutator (setter) | procedure | Updates the value of a private attribute. Can include validation. |
| ToString | function | Returns a string representation of the object's state — used for display. |
| Auxiliary | private | Internal helper methods used by other methods, not accessible from outside. |
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.
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
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.
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.
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
- Go to File → New → Unit – Delphi to create a new blank unit.
- Save it in the same folder as your project (e.g.
UCar.pas). - Type the class structure in the
interfacesection (see template below). - Press Ctrl+Shift+C — Delphi auto-generates the method bodies in the
implementationsection. - Fill in the code inside each method body.
- In your main form unit, add the unit name to the
usesclause (e.g.uses ..., UCar;).
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
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:
constructor TCat.Create;
begin
fName := '';
fAge := 0;
fWeight := 0;
end;Parameterised Create(...) | Non-parameterised Create | |
|---|---|---|
| Values set | Immediately, from the arguments passed in | Default/empty — must be set afterwards |
| When you'd use it | You already know the object's details when creating it | You'll fill in the details later, or the user will type them in afterwards |
"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.
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
// 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'
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
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.
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.
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.
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;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.
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.
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.
function TLibraryBook.IsAvailable : boolean;
begin
Result := (fCopies > 0) and (fWear < 8); // a copy is left AND it is in fair condition
end;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.
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 ...
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:
- FormCreate — set the variable to
nil: "no object exists yet". - Before replacing an object —
Freethe old one, set the variable tonil, then create the new one. If you skip theFree, the old object stays in memory with nothing pointing to it (a memory leak). - FormDestroy —
Freethe object and set the variable tonilwhen the form closes.
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;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
- Create the object from its class, passing the owner (usually the form).
- Set the Parent so Delphi knows where to draw it (which form/panel).
- Set properties like position, size and caption.
- Assign an event handler so it actually does something when clicked.
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 (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).
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.