A school app tracks thousands of students. Each has a name, a year group and grades, and each can enrol on a course or receive a grade. Separate variables for…
English narration · English and 中文 subtitles you can switch
7.1
Scope and prerequisites
This handout teaches Theme B3, Object-oriented programming, for the course first assessed in 2027, using Python, with Java shown where its syntax differs. Sections marked AHL are for Higher Level only.
Prerequisites: B2 Programming (variables, selection, loops, functions and parameters). The examples are fictional models, not real bank systems.
7.2
Classes and objects
Why model the world as objects?
A school app tracks thousands of students. Each one has a name, a year group and a list of grades, and each can enrol on a course or receive a grade. Writing separate variables for every student is impossible. Instead we write the design once, as a class, and make one object per student.
A blueprint: a class is a template that defines how objects of that type are built
Class, object and instance
A class 类 is a blueprint: it defines the attributes 属性 (the data each object holds) and the methods 方法 (what each object can do). An object 对象 is one thing built from that blueprint, an instance 实例 of the class. Making an object is instantiation 实例化.
One class, many objects: the same attributes, each with its own values
An object's state 状态 is the current values of its attributes; its behaviour 行为 is what its methods do.
Objects of a class normally share its defined interface and may hold different instance values; Python also allows instance attributes to be added dynamically.
The object-initialisation step is often taught with the constructor 构造函数. In normal Python construction, __new__ creates the instance and __init__ initialises its state. In Java it is a method with the class's name: public Account(String owner, double balance).
self is the object the method is working on: a_li.deposit(15.0) changes a_li's balance only.
A variable holds a reference 引用 to an object. After c = a_li, both names refer to the same object: a deposit through c is seen through a_li.
Instance and static members
An instance attribute 实例属性 belongs to one object. A static 静态 (class) attribute belongs to the class and is shared by every object.
class Account:
count = 0 # static: one value for the whole class
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
Account.count = Account.count + 1
After two accounts are made, Account.count is 2. In Java a static member is marked static and is called on the class, such as Math.sqrt(9).
Explore
One deposit changes one object
Start with balances 40 and 20. Depositing 15 into A changes A to 55 while B remains 20; both objects use the same class interface.
Encapsulation 封装 bundles the data and the methods that act on it into one class, and hides the data so it can be changed only through those methods. The class then protects its own rules, such as "the balance is never negative".
A UML class diagram: name, attributes, methods; - private, + public
Access
Java
Python convention
Who can use it
private 私有
private
leading _ marks non-public use by convention
Java restricts access; Python's single underscore does not enforce privacy
public 公有
public
plain name
any code
Accessors and mutators
Private attributes are read through an accessor 访问器 (getter) and changed through a mutator 修改器 (setter), which can check the new value first.
To design a class from a scenario, pick out the nouns that are data (attributes) and the verbs that are actions (methods).
A library lends books. Each book has a title, an ISBN and whether it is on loan. A book can be lent and returned.
Attributes (private)
Methods (public)
title: String
lend(): bool
isbn: String
give_back(): void
on_loan: bool
is_on_loan(): bool
lend returns False if the book is already on loan, so the rule "a book cannot be lent twice" lives inside the class.
Nouns become attributes, verbs become methods, and the rule lives inside the class
Advantages and limits of OOP
Advantages
Disadvantages
models real things, so designs are easy to discuss
more code and planning for a small program
classes are reused in other programs
objects can use more memory
encapsulation protects data
a poor class design is hard to change later
7.5
AHL: Inheritance and polymorphism
Inheritance
Inheritance 继承 lets a subclass 子类 take the attributes and methods of a superclass 父类 and add or change some. It models an "is a" relationship: a circle is a shape.
import math
class Shape:
def __init__(self, colour):
self.colour = colour
def area(self):
return 0.0
class Circle(Shape):
def __init__(self, colour, radius):
super().__init__(colour) # run the superclass constructor
self.radius = radius
def area(self): # overrides Shape.area
return math.pi * self.radius ** 2
class Rectangle(Shape):
def __init__(self, colour, width, height):
super().__init__(colour)
self.width, self.height = width, height
def area(self):
return self.width * self.height
super() calls the superclass's version, so the colour code is written once.
In Java: class Circle extends Shape.
Polymorphism
Polymorphism 多态 means one call works on objects of different classes, each running its own version. A subclass method with the same name and parameters as the superclass's overrides 重写 it.
Polymorphism: the same method call runs each object's own code
shapes = [Circle("red", 1.0), Rectangle("blue", 2.0, 3.0)]
for s in shapes:
print(round(s.area(), 2)) # 3.14, then 6.0
The loop does not need to know which kind of shape it holds. A new subclass such as Triangle works with the same loop unchanged.
Overloading 重载 is different: several methods in one class share a name but take different parameters, such as two Java constructors Account(String owner) and Account(String owner, double balance). Python does not overload; it uses default parameter values instead.
Abstract classes
An abstract class 抽象类 cannot be instantiated: it exists to be inherited. An abstract method 抽象方法 must be implemented before a subclass can be concrete; Java abstract declarations have no body, while a Python abstract method may supply a body for reuse. Shape should be abstract, since a plain shape has no sensible area.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
Shape() now raises an error; Circle must define area or it cannot be instantiated either. In Java: abstract class Shape and abstract double area();.
Composition and aggregation
Relationship
Meaning
Example
UML
inheritance
"is a"
a Circle is a Shape
hollow triangle
composition 组合
"has a"; the part dies with the whole
a Drawing has its Shapes
filled diamond
aggregation 聚合
"has a"; the part lives on alone
a Team has Players
hollow diamond
Prefer composition when the relationship is "has a": a car has an engine, it is not a kind of engine. Deep inheritance chains are hard to change, because a change to a superclass affects every subclass.
Design patterns
A design pattern 设计模式 is a tested solution to a common design problem.
Pattern
Problem it solves
Idea
singleton
exactly one object is needed, such as a settings store
the class makes its single instance and always returns it
factory
the code should not depend on which subclass is made
one method decides which subclass to create
observer
several objects must react when one changes
the subject keeps a list of observers and notifies each
Explain the difference between a class and an object, using a phone model as an example.
For the Account class with deposit, state the output of: x = Account("Ana", 10.0), y = Account("Bo", 10.0), x.deposit(5.0), print(x.get_balance(), y.get_balance()).
p = Account("Kai", 30.0), q = p, q.deposit(20.0). State p.get_balance() and explain.
Explain why balance is made private and changed only through withdraw.
Draw the UML class diagram for a Thermostat with a private target (an integer), a constructor, and public methods raise_by(d), lower_by(d) and get_target().
From the scenario "A cinema has screens. Each screen has a number and a number of seats; seats can be booked and cancelled", identify two attributes and two methods of Screen.
State one advantage and one disadvantage of OOP.
AHL A Dog and a Cat both inherit from Animal, which has speak(). Explain how polymorphism lets one loop make every animal in a list speak.
AHL Distinguish overriding from overloading.
AHL State whether each is inheritance, composition or aggregation: (a) a Car and its Engine, made and scrapped together; (b) a Truck and Vehicle; (c) a Club and its Members, who can leave and join other clubs.
Answers.
The class is the design (the phone model): it says what every phone has and can do. An object is one actual phone built from it, with its own state, such as its own battery level.
15.0 10.0: each object has its own balance.
50.0: q = p copies the reference, so p and q are the same object.
Encapsulation: no code outside the class can set the balance to an invalid value; withdraw checks every change, so the rule "never negative" always holds.
Advantage: e.g. classes can be reused, or data is protected by encapsulation. Disadvantage: e.g. more planning and code for a small program.
Each subclass overrides speak(). The loop calls a.speak() on each Animal; at run time each object runs its own class's version, so dogs bark and cats meow without the loop testing the type.
Overriding: a subclass redefines a superclass method with the same name and parameters. Overloading: methods in one class share a name but take different parameters.
(a) composition; (b) inheritance (a truck is a vehicle); (c) aggregation.
7.7
Exam tips
Use the words exactly: a class is the blueprint, an object is an instance, instantiation makes it.
In a UML class diagram, keep three compartments and mark each member - private or + public, with types.
When you "explain encapsulation", say both parts: data and methods bundled together, and the data hidden behind methods that validate it.
In code questions, remember that assigning an object variable copies the reference, not the object.
Mutators normally return nothing (void); accessors return a value and change nothing.
AHL For inheritance answers, name the "is a" test; for composition, the "has a" test.
AHL Polymorphism answers need an example: the same call, different classes, each running its own overridden method.