Programming with Objects

OOP Inheritance

Part 4 of the Paper 4 OOP chapter — inheritance (is-a: a child class reuses a parent), super() to reuse the parent constructor, method overriding to change behaviour, and polymorphism so one loop can call the same method on a mixed list of objects. Ends with a full exam-style Person/Student/Teacher program reading from a file with exception handling.

24.1 Introduction to Inheritance

A teacher and a student are both people: they share a name and an age, and both can introduce themselves. Writing that shared code twice is wasteful. Inheritance lets you write the shared parts once in a parent class, then create child classes that automatically get them and add their own extras.

By the end of this page you will define a parent class, build a child class that inherits from it, reuse the parent's constructor with super(), override a method to change its behaviour, and use polymorphism so a single loop can call the same method on a mixed list of objects.

What this page covers
  • Inheritance, SUPER, method overriding and polymorphism.
  • It builds on classes from Part 1 and encapsulation from Part 2.
TermMeaning
InheritanceA child (sub) class automatically gets the attributes and methods of a parent (super) class. The relationship is "is-a": a Car is a Vehicle.
Superclass (parent)The class that provides the shared attributes and methods.
Subclass (child)The class that inherits from the parent and may add or change features.
super()In Python, a way to call the parent class’s method — most often its constructor. In pseudocode the keyword is SUPER.
Method overridingA child class redefining a method it inherited, so its own version runs instead.
PolymorphismCalling the same method name on different objects and getting each class’s own behaviour.

24.2 Inheritance — Reusing a Parent Class

Why are we doing this?
  • Mark scheme: Without inheritance you copy the same attributes and methods into every related class, and a change means editing them all.
  • Inheritance writes the shared code once in the parent and hands it to every child.
  • Cambridge lists inheritance as core OOP terminology and examines child classes directly in Paper 4.
Exam tip:
  • Examiner focus: Inheritance is part of the OOP characteristics tested on Paper 3 (e.g. matching paradigms to “class, inheritance, encapsulation and polymorphism”) and is written in Paper 4.
  • The Pseudocode Guide gives the keywords INHERITS and SUPER.

In Python a child class names its parent in brackets: class Car(Vehicle). The child then has every attribute and method of Vehicle for free, and can add its own.

class Vehicle:                       # parent (superclass)
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model
    def start(self):
        print(self.brand, self.model, "is starting.")

class Car(Vehicle):                  # child inherits Vehicle
    def __init__(self, brand, model, doors):
        super().__init__(brand, model)   # reuse parent constructor
        self.doors = doors
    def honk(self):
        print(self.brand, "goes beep!")

car = Car("Toyota", "Corolla", 4)
car.start()    # inherited from Vehicle
car.honk()     # defined in Car

The pseudocode equivalent uses the keyword INHERITS:

CLASS Vehicle
    PRIVATE Brand : STRING
    PUBLIC PROCEDURE NEW(GivenBrand : STRING)
        Brand <- GivenBrand
    ENDPROCEDURE
ENDCLASS

CLASS Car INHERITS Vehicle
    PRIVATE Model : STRING
    PUBLIC PROCEDURE NEW(GivenBrand : STRING, GivenModel : STRING)
        SUPER.NEW(GivenBrand)
        Model <- GivenModel
    ENDPROCEDURE
ENDCLASS

Person → Teacher and Student (is-a)

Person

name, age

introduce()

is-a →

Teacher

+ subject

+ teach()

Student

+ examMark

+ study()

Teacher and Student inherit name, age and introduce() from Person, then add their own features.

Key rule
  • A child class is written class Child(Parent) in Python or CLASS Child INHERITS Parent in pseudocode.
  • It gets all the parent's attributes and methods, and can add more.
  • Use it only for an “is-a” relationship.
Exam tip:
  • Inheritance is for “is-a”.
  • If the relationship is “has-a” (a Car has an Engine), that is containment, not inheritance — see the Containment page.
  • Mixing them up is a classic design error examiners look for.

24.3 SUPER and Method Overriding

Why are we doing this?
  • A child usually needs the parent to set up its shared attributes — repeating that code defeats the point of inheritance.
  • super() calls the parent's constructor so the child reuses it.
  • Overriding then lets the child replace an inherited method with its own version when the behaviour should differ.

Inside the child constructor, super().__init__(...) runs the parent constructor first, then the child adds its extra attribute. To override, the child simply defines a method with the same name — its version runs instead of the parent's.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def introduce(self):
        print("I am", self.name)

class Teacher(Person):
    def __init__(self, name, age, subject):
        super().__init__(name, age)    # reuse parent constructor
        self.subject = subject
    def introduce(self):               # override
        print("I am", self.name, "and I teach", self.subject)

t = Teacher("Mrs Rahman", 42, "Computer Science")
t.introduce()
# Output: I am Mrs Rahman and I teach Computer Science
Task — Worked Example — Student inherits Person [4 marks]
Write program code (AO3). A Student class inherits from Person(name, age). Add a constructor that also takes exam_mark, reusing the parent constructor. [4]
Hint:
  • Step 1 — inherit: class Student(Person):.
  • Step 2 — call parent: super().__init__(name, age).
  • Step 3 — add extra: store exam_mark.
Your Turn — Your Turn — Truck inherits Vehicle [4 marks]
Write program code (AO3). A Truck class inherits from Vehicle(brand, model). Add a constructor that also takes cargo, reusing the parent constructor. [4]
Hint:
  • Mirror the Student example.
Key rule
  • Call the parent constructor with super().__init__(...) (Python) or SUPER.NEW(...) (pseudocode) before adding the child's own attributes.
  • To override, define a method with the same name in the child.
Exam tip:
  • A child constructor that forgets super().__init__() loses the parent's attributes — the object will be missing name/age and later code will crash.
  • The examiner specifically checks for the SUPER call.

24.4 Polymorphism

Why are we doing this?
  • Once several classes share a method name, you can treat their objects the same way and let each one behave differently — that is polymorphism.
  • It means one loop can call introduce() on a mixed list of teachers and students, and each prints its own version.
  • This is where overriding pays off.
Exam tip: Examiner focus: Polymorphism is one of the OOP characteristics named in the syllabus and appears in paradigm-matching questions on Paper 3 (“programs using the concepts of class, inheritance, encapsulation and polymorphism”).

Put different objects in one list and loop over them, calling the shared method. Python runs each object's own overridden version automatically.

people = [Teacher("Mrs Rahman", 42, "CS"),
          Student("Rumaisa", 17, 90),
          Student("Aymaan", 17, 78)]

for person in people:
    person.introduce()     # each runs its own version
Task — Worked Example 20.1.11B — Dog and Cat speak()
An Animal has speak() printing a generic sound; Dog and Cat override it. What does the loop print?
Hint:
  • Each object runs its own speak().
Your Turn — Your Turn 20.1.11B — Lion and Elephant get_details()
Lion and Elephant both override get_details(). What does a loop over [Lion(), Elephant()] output?
Hint:
  • Polymorphism picks each object's own version.
Key rule
  • Polymorphism = the same method call (person.introduce()) produces different behaviour depending on the object's class.
  • It works because each subclass overrides the shared method.
Exam tip: To explain polymorphism in words, link it to overriding: the subclasses share a method name but each provides its own implementation, so a single call can produce many behaviours.

24.5 Full Exam-Style Question

Paper 4 · inheritance + file + array · ~16 marks
  • A school stores people in PeopleData.txt.
  • Each line is either a student S,Rumaisa,17,90 or a teacher T,Mrs Rahman,42,Computer Science.

(a) Write a base class Person with attributes Name and Age, a constructor, and a procedure DisplayDetails() that outputs them. [4]

(b) Write a class Student that inherits Person, adds ExamMark, uses the parent constructor, and overrides DisplayDetails() to also output the mark. [4]

(c) Write a procedure ReadData() that reads each line of PeopleData.txt to the end of file, splits on commas, builds a Student for S lines and a Teacher for T lines, stores each in PeopleArray, increments TotalPeople, and uses exception handling. [8]

Lab Task — Show full solution & mark scheme
Reveal the model solution and mark scheme for parts (a)–(c).
Hint:
  • (a) Person: __init__(self, name, age) storing Name and Age; DisplayDetails prints both.
  • (b) Student(Person): __init__ with extra ExamMark, super().__init__(name, age), override DisplayDetails to also print Mark.
  • (c) try: open; while line != "": parts = split(","); if parts[0]=="S": Student else Teacher; store in PeopleArray; TotalPeople += 1; readline; close; except: print error.

Key Points Summary

Inheritance lets you write shared code once in a parent class; child classes automatically get the parent's attributes and methods and can add their own.
Inheritance is an "is-a" relationship: a Car is a Vehicle, a Student is a Person. Use containment (has-a) for "has-a" relationships — do not mix them up.
In Python a child class names its parent in brackets: class Car(Vehicle):. The child gets every attribute and method of Vehicle for free.
In Cambridge pseudocode the keyword is INHERITS: CLASS Car INHERITS Vehicle.
The superclass (parent) provides the shared attributes and methods; the subclass (child) inherits them and may add or change features.
super().__init__(...) (Python) or SUPER.NEW(...) (pseudocode) calls the parent's constructor so the child reuses it — call it before adding the child's own attributes.
Method overriding is when a child class redefines a method it inherited (same name) — the child's version runs instead of the parent's.
A child constructor that forgets super().__init__() loses the parent's attributes — the object will be missing name/age and later code will crash. Examiners check for the SUPER call.
Polymorphism means the same method call (person.introduce()) produces different behaviour depending on the object's class.
Polymorphism works because each subclass overrides the shared method — the subclasses share a method name but each provides its own implementation.
To use polymorphism, put different objects in one list and loop calling the shared method — Python runs each object's own overridden version automatically.
Inheritance is for "is-a" (a Student is a Person); containment is for "has-a" (a Car has an Engine). Mixing them up is a classic design error examiners look for.
A child class can add its own attributes and methods in addition to what it inherits — e.g. Car inherits start() from Vehicle and adds honk().
In the exam, inheritance is routinely combined with file processing and exception handling — read records, build child objects based on a type field (S/T), store in an array.
To override a method, simply define a method with the same name in the child — no special keyword is needed in Python.

24.6 Practice Tasks

Fifteen exam-style tasks. Click Hint for bullet-point guidance, then Help to reveal a worked Python solution.

1Practice Task — Inherit and add an attribute [4 marks]
A class Vehicle has __init__(self, brand, model). Write a class Motorcycle(Vehicle) that also takes has_sidecar, reusing the parent constructor.
2Practice Task — Override a method [3 marks]
A class Animal has speak(self) printing "...". Write a class Dog(Animal) that overrides speak() to print "Woof Woof".
3Practice Task — Inherit, super, override [6 marks]
A class Person has __init__(self, name, age) and greet(self) printing "Hello". Write a class Student(Person) that adds exam_mark (via super) and overrides greet() to also print the mark.
4Practice Task — Polymorphism trace [3 marks]
Given animals = [Dog(), Cat(), Dog()] and a loop calling a.speak() (Dog prints "Woof Woof", Cat prints "Meow"), what is the output?
5Practice Task — is-a or has-a? [4 marks]
Classify each as is-a (inheritance) or has-a (containment): (i) A Car is a Vehicle, (ii) A Car has an Engine, (iii) A Dog is an Animal, (iv) A House has Rooms.
6Practice Task — Define inheritance [2 marks]
Define the term inheritance.
7Practice Task — Define polymorphism [2 marks]
Define the term polymorphism.
8Practice Task — Spot the bug: missing super [3 marks]
This Student constructor crashes later when greet() uses self.name. Why? `class Student(Person): def __init__(self, name, age, mark): self.exam_mark = mark`
9Practice Task — Pseudocode inheritance [4 marks]
In Cambridge pseudocode, declare a class Vehicle with PRIVATE Brand, a constructor NEW, and a class Car INHERITS Vehicle that calls SUPER.NEW and adds Model.
10Practice Task — Polymorphism loop [4 marks]
Write a list of [Teacher("Ms R", 40, "CS"), Student("Adri", 17, 85)] and a loop that calls introduce() on each. Teacher prints "I teach CS", Student prints "I got 85".
11Practice Task — Inherit + add method [5 marks]
A class Shape has __init__(self, colour). Write a class Rectangle(Shape) that adds width and height (via super), and a method area() returning width * height.
12Practice Task — Override with super call [4 marks]
A class Account has deposit(self, amount) that adds to balance. Write a class SavingsAccount(Account) that overrides deposit() to add amount PLUS 1% interest, reusing the parent deposit.
13Practice Task — Why super()? [2 marks]
Explain why a child constructor should call super().__init__().
14Practice Task — Full inheritance hierarchy [10 marks]
Write a base class Employee(name, salary) with a display() method. Write a Manager(Employee) that adds department (via super) and overrides display() to also print the department. Create a Manager and call display().
15Practice Task — Exam-style: Person/Student/Teacher with file [16 marks]
(a) Write Person(name, age) with DisplayDetails [4]. (b) Write Student(Person) adding ExamMark, super, override DisplayDetails [4]. (c) Write ReadData() reading S/T lines from PeopleData.txt, building Student/Teacher, storing in PeopleArray, with exception handling [8].

Question Bank

Answer all questions, then press Submit Quiz to see your score.

0/12 answered

Question 1Multiple Choice

Inheritance is a relationship like:

Question 2Multiple Choice

In Python, a child class is written:

Question 3True / False

In pseudocode, a child class is written CLASS Child INHERITS Parent.

Question 4Multiple Choice

What does super().__init__(...) do?

Question 5Multiple Choice

Method overriding is:

Question 6Multiple Choice

Polymorphism means:

Question 7True / False

A child constructor that forgets super().__init__() loses the parent's attributes.

Question 8Multiple Choice

Which relationship is inheritance (is-a)?

Question 9Multiple Choice

How does polymorphism work in a loop?

Question 10Multiple Choice

In pseudocode, the parent constructor is called with:

Question 11Multiple Choice

To override a method, the child:

Question 12Multiple Choice

Given animals = [Dog(), Cat(), Dog()] and a loop calling a.speak(), what is the output?

Answer all 12 questions to enable submission.