AQA 7517, section 4.1.2.3
Object-oriented programming (OOP) organises a program as a set of objects that model things in the problem, such as a student, a car or an enemy in a game. Each object holds its own data and the code that works on that data.
Why is the object-oriented paradigm used?
- It models real-world things naturally, so programs are easier to design and understand.
- Data is hidden inside objects, which protects it from accidental changes.
- Code can be reused through inheritance and composition.
- Large programs are easier to maintain, because a change to a class is made in one place.
- Different programmers can work on different classes.
Class and object
A class is a blueprint. It defines the attributes (data fields or properties) and methods (subroutines) that the objects based on it will have. It captures the common behaviour and characteristics of those objects.
An object is one particular instance of a class, with its own values for the attributes.
Creating an object from a class is called instantiation. This is done with a constructor, which is a special method that sets up the new object. The object is stored in a variable, which holds a reference to it.
class Dog:
def __init__(self, name, age): # the constructor
self.name = name # attributes
self.age = age
def speak(self): # a method
return self.name + " says woof"
rex = Dog("Rex", 4) # instantiation
fido = Dog("Fido", 2)
print(rex.speak()) # Rex says woof
Here Dog is the class, and rex and fido are two objects, each with their own name and age.
Encapsulation
Encapsulation means bundling data and methods together in a class and hiding the internal details, so the data can only be changed through the object's methods. This protects the data and means the inside of a class can be changed without breaking other code.
Access is controlled by access specifiers:
| Specifier | UML symbol | Who can access it |
|---|---|---|
| Public | + |
Any code |
| Private | - |
Only the class itself |
| Protected | # |
The class and its subclasses |
class Account:
def __init__(self):
self.__balance = 0 # private (double underscore)
def deposit(self, amount):
if amount > 0:
self.__balance = self.__balance + amount
def get_balance(self):
return self.__balance
Other code can't set the balance to anything it likes. It must use deposit, which checks the amount. (Python doesn't strictly enforce privacy. Names starting with __ are made harder to reach, and a single _ marks something as "protected" by convention. Languages such as Java and C# enforce private and protected exactly.)
Inheritance
Inheritance lets a new class (the subclass, or child) take on the attributes and methods of an existing class (the superclass, or parent), and add its own. It avoids repeating code.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Cat(Animal): # Cat inherits from Animal
def speak(self):
return self.name + " says meow"
Cat automatically has name from Animal. It is an "is a" relationship: a cat is an animal.
Polymorphism and overriding
Overriding is when a subclass provides its own version of a method that it inherited, replacing the superclass version. In the example above, Cat.speak overrides Animal.speak.
Polymorphism ("many forms") means the same method call can behave differently depending on the type of object it is called on.
class Dog(Animal):
def speak(self):
return self.name + " says woof"
pets = [Dog("Rex"), Cat("Tom"), Animal("Thing")]
for p in pets:
print(p.speak())
This prints:
Rex says woof
Tom says meow
...
The loop calls p.speak() in exactly the same way each time, and the correct version runs for each object. The code doesn't need to check the type.
Related method terms you may meet:
- Abstract method: declared in a superclass with no body. Each subclass must provide its own version.
- Virtual method: a method that can be overridden by subclasses.
- Static method: belongs to the class itself, not to any one object, so it can be called without creating an object.
Aggregation and composition
Both describe a "has a" relationship, where an object is made from other objects. They differ in how tightly the parts are tied to the whole.
- Aggregation: the parts can exist without the whole. A school has teachers, but the teachers still exist if the school closes.
- Composition: the parts cannot exist without the whole. A house has rooms, and if the house is destroyed, the rooms go with it.
class Engine:
pass
class Car:
def __init__(self):
# Composition: the car creates and owns its engine
self.engine = Engine()
Class diagrams
A class diagram (in UML) shows classes and how they relate. Each class is a box with three sections: the class name, its attributes and its methods. The specifier symbols +, - and # go in front of each.
Reading it: Cat inherits from Animal (the line points to the superclass). Cat overrides speak(). name is protected, so Cat can use it, while lives is private to Cat.
For relationships between separate classes:
- A line with a white (hollow) diamond at the whole's end is aggregation.
- A line with a black (filled) diamond at the whole's end is composition.
Object-oriented design principles
Three principles guide good design:
- Encapsulate what varies. Find the parts of the program that are likely to change and put them in their own classes, so changes don't spread through the code.
- Favour composition over inheritance. Building objects from other objects is usually more flexible than long inheritance chains, which tie classes closely together.
- Program to interfaces, not implementation. Write code that depends on what an object can do (its public methods) rather than how it does it, so one implementation can be swapped for another.
Worked example
Task: model a shop where every item has a name and price, and food items also have a number of calories.
class Item:
def __init__(self, name, price):
self.name = name
self.price = price
def describe(self):
return self.name + ": £" + str(self.price)
class FoodItem(Item):
def __init__(self, name, price, calories):
super().__init__(name, price)
self.calories = calories
def describe(self):
base = Item.describe(self)
return base + ", " + str(self.calories) + " kcal"
basket = [Item("Pen", 1.2), FoodItem("Apple", 0.5, 52)]
for thing in basket:
print(thing.describe())
Output:
Pen: £1.2
Apple: £0.5, 52 kcal
How it uses the ideas:
Itemis the superclass andFoodItemthe subclass, which inheritsnameandprice.FoodItemoverridesdescribeto add the calories.- The loop shows polymorphism: the same call
thing.describe()runs a different version for each object. Item("Pen", 1.2)is instantiation, which uses the constructor__init__.
Exam tip: always give an example from the scenario in the question when you explain a term. "Polymorphism means the same method behaves differently for different classes, such as speak() giving different sounds for Dog and Cat" is stronger than a definition alone.
Check yourself
What is the difference between a class and an object?
A class is a blueprint that defines the attributes and methods. An object is a particular instance of the class, with its own values.
What is encapsulation and why is it useful?
Bundling data and methods in a class and hiding the data so it can only be accessed through methods. It protects the data from accidental or invalid changes and lets the inside of the class change without affecting other code.
What is the difference between aggregation and composition?
In aggregation the part can exist without the whole (a teacher and a school). In composition the part cannot exist without the whole (a room and a house). In UML, aggregation uses a white diamond and composition a black diamond.
What is overriding?
When a subclass provides its own version of a method that it inherited from its superclass, replacing the superclass version.
What do the symbols +, - and # mean on a class diagram?
+ is public, - is private and # is protected.
Give one reason why "favour composition over inheritance" is advised
Composition is more flexible, because objects can be combined and changed without being locked into a rigid inheritance hierarchy where changes to a superclass affect all subclasses.