OCR H446, section 2.2.1 (f)
Object-oriented programming (OOP) organises a program around objects, which combine data and the code that works on it. It suits large programs that model real-world things.
Key terms
| Term | Meaning |
|---|---|
| Class | A blueprint that defines the attributes and methods of a kind of object |
| Object | One instance of a class, with its own values |
| Attribute (property) | A variable that belongs to an object (its data) |
| Method | A subroutine that belongs to a class (its behaviour) |
| Constructor | A special method that runs when an object is created, setting up its attributes |
| Instantiation | Creating an object from a class |
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", 3) # instantiation
fido = Dog("Fido", 5) # a second object
print(rex.speak()) # Rex says Woof
OCR pseudocode:
class Dog
private name
private age
public procedure new(givenName, givenAge)
name = givenName
age = givenAge
endprocedure
public function speak()
return name + " says Woof"
endfunction
endclass
rex = new Dog("Rex", 3)
In OCR pseudocode, attributes and methods are public unless marked private, and methods are called as object.method(), for example rex.speak().
Encapsulation
Encapsulation means bundling the data and methods together, and controlling access to the data. Attributes are made private, so they can only be used through public methods.
class Account:
def __init__(self, balance):
self.__balance = balance # private (name mangling)
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def get_balance(self):
return self.__balance
Why:
- The data can't be put into an invalid state by outside code (the
depositmethod validates). - The inside can change without affecting the code that uses the class.
- It hides complexity: the user of the class only needs the public methods. This is abstraction (2.1.1).
Public methods used to read and change private attributes are getters and setters.
Inheritance
A subclass (child) inherits the attributes and methods of a superclass (parent), and can add new ones or override inherited ones. This reuses code (2.1.2 (d)).
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Cat(Animal): # Cat inherits from Animal
def speak(self): # overrides speak
return self.name + " says Meow"
class Fish(Animal):
pass # uses Animal's speak as is
OCR pseudocode uses inherits and super:
class Cat inherits Animal
public procedure new(givenName)
super.new(givenName)
endprocedure
public function speak()
return name + " says Meow"
endfunction
endclass
An inheritance diagram has the superclass at the top, with arrows from the subclasses pointing up to it ("is a" relationship: a Cat is an Animal).
Polymorphism
Polymorphism ("many forms") means the same method name can behave differently for different classes. A program can treat objects of different subclasses in the same way, and each does its own version:
animals = [Cat("Tom"), Fish("Nemo"), Animal("Generic")]
for a in animals:
print(a.speak())
Output:
Tom says Meow
...
...
The code doesn't need to know which kind of animal each one is. A new subclass can be added without changing this loop. This is overriding polymorphism. Overloading (several methods with the same name but different parameters) is another form that some languages support.
Benefits of OOP
- Models the real world naturally.
- Reuse through inheritance, and objects can be used in many programs.
- Encapsulation protects data and reduces errors.
- Easier to maintain: changes are limited to one class.
- Good for large projects and teams.
Drawbacks: it can be more complex for small programs, may use more memory, and the design takes more planning up front.
Class diagram
Worked example
Task: a school system has students and teachers. Both have a name and an ID, but a student also has a year group and a teacher has a subject. Design classes using inheritance.
- Superclass
Person: attributesname,pid. Methoddescribe(). - Subclass
Student: inheritsnameandpid; addsyear. - Subclass
Teacher: inheritsnameandpid; addssubject.
class Person:
def __init__(self, name, pid):
self.name = name
self.pid = pid
def describe(self):
return f"{self.name} ({self.pid})"
class Student(Person):
def __init__(self, name, pid, year):
super().__init__(name, pid)
self.year = year
def describe(self):
return super().describe() + f", Year {self.year}"
class Teacher(Person):
def __init__(self, name, pid, subject):
super().__init__(name, pid)
self.subject = subject
s = Student("Amy", 101, 12)
t = Teacher("Mr Lee", 7, "Computing")
print(s.describe()) # Amy (101), Year 12
print(t.describe()) # Mr Lee (7)
Why inheritance: name, pid and part of describe are written once in Person. Student overrides describe to add the year, which is polymorphism.
Exam tip: define terms precisely and give an example from the scenario ("Student inherits the name attribute from Person"). To explain encapsulation, say that attributes are private and accessed through methods, and say why that helps.
Check yourself
What is the difference between a class and an object?
A class is a blueprint that defines attributes and methods. An object is an instance of a class, with its own values.
What is encapsulation, and why is it useful?
Bundling data and methods together and making attributes private, so they can only be changed through public methods. It protects the data from invalid changes and hides the inner workings.
What is inheritance?
A subclass takes on the attributes and methods of a superclass, and can add to them or override them, so code is reused.
What is polymorphism?
The same method name behaves differently depending on the class of the object, so different kinds of object can be used in the same way.
What does a constructor do?
It runs when an object is created, and sets up its attributes.