Computer ScienceCore18 min read

Object-Oriented Programming

Four ideas that organise large programs

This topic appears in:

01

Why OOP exists

A small program can be a list of instructions. A large one cannot — with thousands of variables floating in one scope, every change risks breaking something far away.

OOP's answer is to bundle data together with the code that operates on it, and then hide the internals so the rest of the program cannot reach in and corrupt them.

02

Class versus object

A class is the blueprint. An object is a house built from it. One class, many objects, each with its own values.

class Student defines that every student has a name, a roll number and a marks list. Student ali = new Student("Ali", 42) creates one actual student. Creating a second student does not disturb the first — they hold separate data in separate memory.

03

The four pillars

PillarWhat it meansWhy you want it
EncapsulationFields are private; access goes through methodsNothing can put the object into an invalid state
InheritanceA class extends another and reuses its membersShared behaviour is written once
PolymorphismOne call, many implementationsAdd new types without editing old code
AbstractionExpose what it does, hide howCallers survive changes to the internals

Click each box. Circle and Rectangle both inherit describe() untouched, but each overrides area(). Same call, different behaviour — that is polymorphism.

04

Encapsulation, concretely

Make balance public and any line of code anywhere can set it to −5000. Make it private and force changes through withdraw(), and you get one place to check that the account has sufficient funds.

The rule of thumb: fields private, methods public as needed. The public methods are your contract with the rest of the program.

Polymorphism, in one line

Given a list of Shape objects, calling s.area() on each runs the circle formula for circles and the rectangle formula for rectangles — without a single if-statement. Add a Triangle class next year and that loop still works, unchanged.

Inheritance is not free

Deep inheritance chains get brittle fast — a change five levels up breaks everything below it. Prefer composition: a Car has an Engine, rather than a Car is an Engine. Use inheritance only when the child genuinely is a kind of the parent.

06

Classes, objects and constructors

A class is a blueprint; an object is a thing built from it. The distinction matters because a class is written once and costs nothing at run time, while every object created from it occupies its own memory and carries its own values.

Creating an object is called instantiation, and it runs a special method called the constructor. The constructor exists to leave the new object in a valid state — giving every attribute a sensible starting value, so no object can begin life half-initialised.

CLASS BankAccountPRIVATE balance : REALPRIVATE owner: STRINGPUBLIC PROCEDURE NEW(startOwner, startBalance)owner← startOwnerbalance ← startBalanceENDPROCEDUREPUBLIC PROCEDURE Deposit(amount)IF amount > 0 THEN balance ← balance + amountENDPROCEDUREPUBLIC FUNCTION GetBalance() RETURNS REALRETURN balanceENDFUNCTIONbalance is private, so it can only change through Deposit
CLASS
the blueprintwritten once, uses no memory itself
object
an instanceeach has its own copy of the attributes
NEW
the constructorruns at creation to set a valid initial state

Why the validation belongs inside the class

Because balance is private, no outside code can set it to a negative number directly — every change must go through Deposit, which checks the amount first. The rule is enforced in one place rather than everywhere the account is used, so it cannot be forgotten. That is encapsulation earning its keep rather than being a formality.

07

Getters, setters and why attributes stay private

If attributes are private, controlled access is provided by methods — a getter to read a value and a setter to change it. A setter is not merely a wrapper: it is the place where a rule lives.

A setter can reject an invalid value, adjust related attributes to stay consistent, or record that a change occurred. None of that is possible if outside code writes to the attribute directly, which is the whole argument for keeping it private.

Not every attribute needs both. A read-only property has a getter and no setter, which makes it impossible for any code to change it after construction.

  • Getter — returns the value, often with no logic at all.
  • Setter — validates before assigning, and may reject the change.
  • Read-only — a getter with no setter, so the value is fixed at construction.
  • Derived — a getter that calculates rather than stores, so it can never fall out of step.

A setter that does no checking gains you nothing

Writing a private attribute with a setter that simply assigns whatever it is given provides no more protection than making the attribute public — it is the same access with more code. The point of the setter is the check. In an exam, describe what the setter validates, not just that one exists.

08

Recognising classes in a problem description

Design questions describe a system in words and ask for suitable classes. A reliable starting point is to look for the nouns: things that have both data and behaviour are usually classes, while properties of those things are usually attributes.

A library system mentions books, members and loans. Each has data worth storing and things it can do, so each is a candidate class. A book's title and ISBN are attributes rather than classes, because they carry no behaviour of their own.

Then look for the verbs, which suggest methods, and for relationships. If one thing is a kind of another, that suggests inheritance — a reference book is a kind of book. If one thing has another, that is composition rather than inheritance: a library has books, but a library is not a kind of book.

The is-a versus has-a test

  1. A car is a vehicle → inheritance.
  2. A car has an engine → composition, an attribute holding another object.
  3. Getting this the wrong way round produces classes that inherit from things they merely contain.
  4. Nouns with both data and behaviour become classes; nouns without behaviour become attributes.
  5. Verbs in the description usually become methods.

Practice questions

6 questions · 27 marks · full working on every one

Try each one on paper first, then open the working. The marks are shown where they are actually awarded, because that is where they are actually lost.

Short questions

3 · 7 marks

Two marks each, in the style of the short-question section of the paper. Answer in two or three lines.

SQ1[2 marks]
Explain the difference between a class and an object.
Model answer

A class is the template that defines the attributes and methods. An object is a particular instance of that class, created at run time, with its own values for those attributes.

Examiner tip. "A class is a blueprint, an object is a house built from it" is fine, but name attributes and methods too.

SQ2[2 marks]
State what is meant by encapsulation and give one benefit.
Model answer

Attributes are made private and are accessed only through public methods. This prevents other code from setting an attribute to an invalid value.

Examiner tip. The benefit must be concrete. "It is safer" is not a benefit; "it stops an age being set to −5" is.

SQ3[3 marks]
Explain the difference between overriding and overloading a method.
Model answer

Overriding replaces an inherited method in a subclass with a new version having the same signature. Overloading defines several methods with the same name but different parameter lists in the same class.

Examiner tip. Same signature, different class means overriding. Same class, different parameters means overloading.

Long questions

2 · 15 marks

Theory and numerical together, as they appear in the long-question section.

LQ1[8 marks]
A school system has a base class Person and subclasses Student and Teacher.
  1. Explain what inheritance is and state one advantage of using it here. [3]
  2. Suggest two attributes that belong in Person and one that belongs only in Student. [3]
  3. Explain how polymorphism could be used when printing a list of all people. [2]
Mark scheme
  1. A subclass automatically acquires the attributes and methods of its parent class[1]
  2. Student and Teacher both get name and address without redefining them[1]
  3. Advantage: the shared code is written once, so a change is made in one place[1]
  4. In Person: name[1]
  5. In Person: date of birth or address[1]
  6. In Student only: class or roll number[1]
  7. Each subclass overrides a describe method with its own version[1]
  8. The program calls describe on every item in the list and the correct version runs automatically[1]

Examiner tip. Anything that belongs to every person goes in the base class. If you can name one subclass it does not apply to, it does not belong there.

LQ2[7 marks]
A class BankAccount has a private attribute balance and public methods deposit and withdraw.
  1. Explain why balance is private rather than public. [2]
  2. Describe the validation the withdraw method should perform. [2]
  3. Write pseudocode for the withdraw method. [3]
Mark scheme
  1. Other code cannot change it directly[1]
  2. So every change passes through a method that can validate it, keeping the balance consistent[1]
  3. The amount must be positive[1]
  4. The amount must not exceed the current balance[1]
  5. Method header taking an amount parameter[1]
  6. IF amount > 0 AND amount <= balance THEN subtract and return TRUE[1]
  7. ELSE return FALSE without changing the balance[1]

Examiner tip. A withdraw method that changes the balance and then checks is wrong even if it later corrects itself. Validate first, act second.

Exam questions

1 · 5 marks

Multi-part questions with a full mark scheme.

Q1[5 marks]
A programmer writes Shape s = new Circle(5) where Circle inherits from Shape.
  1. Explain why this statement is allowed. [2]
  2. The Shape class has an abstract method area. Explain what abstract means here and what Circle must do. [3]
Mark scheme
  1. A Circle is a Shape, so an object of the subclass can be held in a variable of the parent type[1]
  2. This lets one variable or array hold objects of several related classes[1]
  3. An abstract method is declared but has no implementation in the base class[1]
  4. No object of the abstract class itself can be created[1]
  5. Circle must provide its own area method, returning π × radius²[1]

Examiner tip. Abstract says "every subclass must supply this, but there is no sensible general version". Area is the standard example: shapes have areas, but there is no formula for a shape in general.