IB Diploma Computer Science · Computational thinking and problem-solving
Object-oriented programming
1Classes and objects
Object-oriented programming (OOP) organises a program around objects, which bundle data and the code that works on that data.
- A class is a blueprint or template, such as
Student. - An object is one instance of a class, such as the student Amara. Many objects can be made from one class, each with its own data.
- Attributes (fields, properties) are the data an object holds: name, year, marks.
- Methods are the actions an object can perform:
add_mark(),average(). - A constructor is a special method that runs when an object is created and sets its starting attributes. In Python it is called
__init__.
class Student:
def __init__(self, name, year):
self.name = name
self.year = year
self.marks = [] def add_mark(self, mark):
self.marks.append(mark)
def average(self):
return sum(self.marks) / len(self.marks)
amara = Student("Amara", 12)
amara.add_mark(72)
amara.add_mark(80)
print(amara.average())
This prints 76.0. self refers to the particular object the method is working on.
Check yourself
What is the difference between a class and an object?
Show the answer
A class is a template; an object is one instance made from it
One Student class can make many student objects.
2Encapsulation
Encapsulation means bundling the data and methods together inside a class and hiding the data from direct access by the rest of the program.
- Attributes are made private so they can only be changed through the class's own public methods.
- Accessor methods ("getters") return a value; mutator methods ("setters") change it, and can validate the new value first.
- In Python, a leading underscore (
_balance) marks an attribute as private by convention; in Java the keywordprivateenforces it.
class Account:
def __init__(self):
self._balance = 0 def deposit(self, amount):
if amount > 0:
self._balance += amount
def get_balance(self):
return self._balance
Nothing outside the class can set the balance to a negative number by mistake, because every change goes through deposit, which checks the amount.
Benefits: data stays valid, the inside of a class can be changed without breaking code that uses it, and errors are easier to trace.
Check yourself
Why are attributes often made private?
Show the answer
So they can only be changed through methods that validate them
This is encapsulation.
3Inheritance
Inheritance lets a new class (the subclass, child or derived class) take on the attributes and methods of an existing class (the superclass, parent or base class), and then add or change its own.
class Animal:
def __init__(self, name):
self.name = name def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return self.name + " says woof"
class Cat(Animal):
def speak(self):
return self.name + " says meow"
DogandCatinheritnameand the constructor fromAnimalwithout rewriting them.- Inheritance models an "is-a" relationship: a dog is an animal.
- Benefits: code is reused, changes to the superclass flow down to all subclasses, and class hierarchies mirror the real world.
- Risk: deep hierarchies become tightly linked, so a change in a superclass can break many subclasses.
UML class diagram: Dog and Cat inherit from Animal and override speak()
Check yourself
Which relationship does inheritance model?
Show the answer
"Is-a", such as a dog is an animal
Has-a is aggregation or composition.
4Polymorphism
Polymorphism ("many forms") means the same method call can behave differently depending on the object's class.
- Overriding: a subclass gives its own version of a method it inherited. Above,
DogandCatboth overridespeak. - The calling code does not need to know which kind of object it has:
pets = [Dog("Rex"), Cat("Tom")]
for pet in pets:
print(pet.speak())
This prints "Rex says woof" then "Tom says meow". New animal classes can be added later without changing this loop.
- Overloading: several methods with the same name but different parameters, such as
area(radius)andarea(width, height). Java supports this directly; Python achieves similar results with default parameters.
Check yourself
Dog and Cat each define their own speak() method in place of Animal's. What is this called?
Show the answer
Overriding
The subclass replaces the inherited version.
5Relationships, abstraction and design
Classes can be related in other ways:
- Aggregation ("has-a", weak): a
TeamhasPlayers, but players still exist if the team is deleted. - Composition ("has-a", strong): a
HousehasRooms, which cannot exist without the house. - Dependency ("uses"): one class uses another briefly, for example as a parameter.
Abstraction in OOP: a class shows only what other code needs (its public methods) and hides how it works. An abstract class cannot be instantiated itself; it defines methods that every subclass must provide (such as a Shape class with an area() method that Circle and Square must implement).
UML class diagrams show each class as a box in three parts: name, attributes and methods. A - marks private members and a + marks public ones. An arrow with a hollow triangle points from a subclass to its superclass.
Advantages of OOP: modular, reusable code; easier teamwork since classes can be built and tested separately; models real-world things naturally; encapsulation protects data.
Disadvantages: more complex to design, can be slower and use more memory, and is unnecessary for small, simple programs.
Check yourself
A Library object holds many Book objects, and the books still exist if the library object is deleted. Which relationship is this?
Show the answer
Aggregation
A weak has-a relationship.
Now test yourself
This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.
Practise in Impera