OCR H446, section 1.2.4 (e)
Object-oriented programming (OOP) builds a program from objects that model things in the problem: a pet, a bank account, a player. Each object bundles together its data and the code that works on it.
The key terms
| Term | Meaning |
|---|---|
| Class | A blueprint that defines the attributes and methods for a kind of object |
| Object | One instance of a class, with its own values |
| Attribute | A piece of data held by an object (a variable inside the class) |
| Method | A subroutine that belongs to a class: what an object can do |
| Constructor | A special method that sets up a new object. In OCR pseudocode, the procedure called new |
| Instantiation | Creating an object from a class |
A class in OCR pseudocode
class Pet
private name
private attempts = 3
public procedure new(givenName)
name = givenName
endprocedure
public function getName()
return name
endfunction
public procedure setAttempts(number)
attempts = number
endprocedure
public function speak()
return "..."
endfunction
endclass
privateandpublicshow access. Attributes and methods are public unless stated.- The constructor is the procedure
new. - Methods are called on an object:
object.method(parameters).
Creating and using objects
myPet = new Pet("Fido")
print(myPet.getName()) // Fido
myPet.setAttempts(5)
myPet is an object (an instance of Pet) with its own name and attempts.
Encapsulation
Encapsulation means bundling the data and methods together in a class, and hiding the internal details, so the data is only accessed through the object's methods.
- Attributes are made
private, so other code cannot read or change them directly. - The class provides public methods (such as
getNameandsetAttempts) that control how the data is used, and can validate it.
public procedure setAttempts(number)
if number >= 0 AND number <= 10 then
attempts = number
endif
endprocedure
Benefits: it protects the data from being set to invalid values, hides complexity, and lets the inside of a class change without breaking the code that uses it.
Inheritance
Inheritance lets a new class (the subclass) take on the attributes and methods of an existing class (the superclass) and add or change its own. It is written with inherits.
class Dog inherits Pet
private breed
public procedure new(givenName, givenBreed)
super.new(givenName)
breed = givenBreed
endprocedure
public function speak()
return "Woof"
endfunction
endclass
Doginheritsname,getNameand the rest fromPet.super.new(givenName)calls the constructor of the superclass. More generally,super.methodName(...)calls a superclass method.- A dog is a kind of pet.
- Benefits: reuse of code, a clear hierarchy, and only the differences need writing.
myDog = new Dog("Fido", "Scottish Terrier")
print(myDog.getName()) // Fido: inherited from Pet
print(myDog.speak()) // Woof: the Dog version
Polymorphism
Polymorphism ("many forms") means the same method call can behave differently depending on the type of object it is called on.
In the example, both classes have a speak method, but Dog overrides the Pet version with its own.
array pets[2]
pets[0] = new Pet("Generic")
pets[1] = new Dog("Fido", "Terrier")
for i = 0 to 1
print(pets[i].speak())
next i
The loop calls pets[i].speak() the same way each time, and the right version runs for each object: ... for the Pet and Woof for the Dog. The code doesn't need to check the type.
Overriding is when a subclass replaces a method inherited from the superclass with its own version.
The same idea in Python
class Pet:
def __init__(self, name):
self.__name = name # private by convention
def get_name(self):
return self.__name
def speak(self):
return "..."
class Dog(Pet): # inheritance
def __init__(self, name, breed):
super().__init__(name)
self.__breed = breed
def speak(self): # overriding
return "Woof"
my_dog = Dog("Fido", "Terrier")
print(my_dog.get_name(), my_dog.speak()) # Fido Woof
Why use object-oriented programming?
- It models real things naturally, which makes large programs easier to design and understand.
- Encapsulation protects data and reduces errors.
- Inheritance and polymorphism give reuse and flexibility.
- A class can be changed in one place, and different programmers can work on different classes.
Worked example
Task: design the classes for a school system with Person, Student and Teacher, and explain the OOP ideas used.
class Person
private name
public procedure new(givenName)
name = givenName
endprocedure
public function getName()
return name
endfunction
public function role()
return "Person"
endfunction
endclass
class Student inherits Person
public function role()
return "Student"
endfunction
endclass
class Teacher inherits Person
private subject
public procedure new(givenName, givenSubject)
super.new(givenName)
subject = givenSubject
endprocedure
public function role()
return "Teacher"
endfunction
endclass
- Encapsulation:
nameisprivate, and accessed only throughgetName. - Inheritance:
StudentandTeacherinherit the name andgetNamefromPerson, andTeacheraddssubject. - Polymorphism and overriding: each class has its own
role(), and callingp.role()on a list of people gives the right answer for each object.
Exam tip: define each term and point to it in the code. Encapsulation: private attributes and public methods. Inheritance: inherits. Polymorphism: the same method call, different behaviour, through overriding. Use super to call the superclass.
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 one instance of the class, with its own values.
What is encapsulation, and why is it useful?
Bundling data and methods together and hiding the data so it is only accessed through methods. It protects the data from invalid changes and lets the inside of the class change without affecting other code.
What does super.new(givenName) do in a subclass constructor?
It calls the constructor of the superclass, passing it the name, so that the inherited attributes are set up.
What is polymorphism?
The same method call behaving differently depending on the type of object it is called on, for example through a subclass overriding a method.