Edexcel International Advanced Level Computer Science, point 13.1.1
Definition
Object-oriented programming (OOP) is a programming paradigm that organises a program as a collection of objects, each combining data (attributes) and the code that works on that data (methods). Objects interact by calling each other's methods.
Function and why needed
OOP models real-world things (a customer, a car, a bank account) and manages the complexity of large programs. It supports reuse, maintenance and teamwork. In Unit 3 you must understand the paradigm and read class diagrams and code. In Unit 4 you write OOP code (20.1.1).
a. Concepts
Abstraction
Showing only what is needed, hiding the detail (10.1.1). A class gives a simple interface (its public methods), hiding how it works inside. A driver uses car.accelerate() without knowing how the engine works.
Class
A class is a blueprint (template) that defines the attributes and methods for a kind of object.
Instantiation
Creating an object (an instance) from a class. Each object has its own values for the attributes.
class Dog:
def __init__(self, name, age): # the constructor
self.name = name
self.age = age
rex = Dog("Rex", 3) # instantiation
fido = Dog("Fido", 5) # another object, own values
Methods and attributes (public, private, protected)
- Attributes are variables belonging to an object (
name,age). Methods are subprograms belonging to a class (speak()). - Access modifiers control who can use them:
| Modifier | UML | Meaning | Python convention |
|---|---|---|---|
| Public | + |
Accessible from anywhere | name |
| Protected | # |
Accessible within the class and its subclasses | _name |
| Private | - |
Accessible only within the class | __name |
(Python relies on conventions and name mangling: other languages such as Java enforce these.)
Encapsulation
Bundling the data and the methods that use it into one unit, and restricting direct access to the data. Attributes are private, and public methods control access (getters and setters).
class BankAccount:
def __init__(self, balance):
self.__balance = balance # private
def deposit(self, amount):
# validation protects the data
if amount > 0:
self.__balance += amount
def get_balance(self):
return self.__balance
Benefits: data can't be set to invalid values, the internal details can change without affecting other code, and errors are easier to trace to one class.
Composition
An object is made up of other objects (a "has-a" relationship). A house has rooms. The parts belong to the whole, and don't exist without it.
class Room:
def lights_on(self):
return "Lights on"
class House:
def __init__(self):
self.room = Room() # House HAS-A Room
def lights_on(self):
return self.room.lights_on()
(Aggregation is a weaker form: the part can exist on its own, such as a team and its players.)
Inheritance
A new class (subclass, child) takes on the attributes and methods of an existing class (superclass, parent), and can add or change some (an "is-a" relationship). This reuses code.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Dog(Animal): # Dog IS-A Animal
# overrides the parent's method
def speak(self):
return self.name + " says Woof"
Polymorphism
The same method call behaves differently depending on the object's class. A program can treat different subclasses in the same way, and each does its own version.
for pet in [Dog("Rex"), Animal("Generic")]:
print(pet.speak()) # Rex says Woof / ...
UML class diagrams
A UML class diagram shows the classes in a program and the relationships between them. (Check the notation in Appendix 2 of the specification.)
A class
Relationships
| Relationship | Meaning | Line |
|---|---|---|
| Association | Classes are linked (a teacher teaches students) | Plain line |
| Directed association | One class uses the other (one direction) | Line with an arrow |
| Inheritance (generalisation) | Subclass "is a" superclass | Line with a hollow triangle pointing at the superclass |
| Composition | "Has a", parts can't exist without the whole | Line with a filled diamond at the whole |
| Aggregation | "Has a", parts can exist alone | Line with a hollow diamond at the whole |
You must be able to interpret and complete UML class diagrams, and identify OOP features implemented in code.
Benefits
- Models real-world things naturally.
- Reuse through inheritance and composition.
- Encapsulation protects data and reduces errors.
- Modular: each class can be developed and tested separately.
- Easier to maintain and extend: a new subclass doesn't change existing code.
- Suits large projects and teams.
Drawbacks
- More complex to design: needs planning (class hierarchy and relationships).
- Can be slower and use more memory than simple procedural code.
- Overkill for small programs.
- A steeper learning curve.
- Deep inheritance hierarchies can become hard to understand (prefer composition where suitable).
Worked example
Task: identify the OOP features in this code.
class Shape:
def __init__(self, colour):
self._colour = colour # protected attribute
def area(self):
return 0
class Circle(Shape): # inheritance
def __init__(self, colour, radius):
super().__init__(colour)
self.__radius = radius # private attribute
def area(self): # overriding (polymorphism)
return 3.14159 * self.__radius ** 2
class Drawing:
def __init__(self):
self.shapes = [] # composition: has shapes
def add(self, shape):
self.shapes.append(shape)
def total_area(self):
return sum(s.area() for s in self.shapes)
d = Drawing() # instantiation
d.add(Circle("red", 2))
d.add(Shape("blue"))
print(d.total_area()) # 12.56636
| Feature | Where |
|---|---|
| Classes | Shape, Circle, Drawing |
| Instantiation | d = Drawing(), Circle("red", 2) |
| Inheritance | Circle(Shape) |
| Encapsulation (private attribute) | self.__radius |
| Protected attribute | self._colour |
| Polymorphism | area() gives a different result for Circle and Shape, and total_area calls it on both without checking the type |
| Composition | Drawing holds a list of shapes |
| Abstraction | total_area() hides how each area is found |
Exam tip: know each concept's definition and a code or diagram example. For UML, learn the symbols for visibility (+, -, #) and the arrow and diamond styles. A common mistake is to confuse inheritance ("is a") and composition ("has a"). When identifying features in code, quote the line.
Check yourself
What is the difference between a class and an object?
A class is a blueprint defining attributes and methods. An object is an instance of a class with its own attribute values, created by instantiation.
What does encapsulation mean?
Bundling data and the methods that use it into one unit, and restricting direct access to the data, usually by making attributes private.
What is the difference between inheritance and composition?
Inheritance is an "is-a" relationship: a subclass takes on the features of a superclass. Composition is a "has-a" relationship: an object is made of other objects.
What does the symbol # mean in a UML class diagram?
A protected attribute or method.
What is polymorphism?
The same method call behaves differently depending on the class of the object it is called on.