B3.2.1

Explain and apply inheritance in OOP to promote code reusability

Inheritance lets a new class ( subclass ) reuse common attributes and methods from an existing class ( superclass ), then add its own specific features.

3 min read444 words

What Is Inheritance?

Inheritance lets a new class (subclass) reuse common attributes and methods from an existing class (superclass), then add its own specific features.

Intuition: Common + Specific

  • Real-world groups share common traits but also have differences.
  • Example idea from the notes:
    • Mammals share warm-blooded, limbs, hair/fur.
    • Vehicles share move/brake/transport behavior.
  • In code, put shared parts once in the superclass; keep subclass-only details in each subclass.

Vehicle Example

  • Vehicle (superclass): common data like fuel_type, capacity, maximum_range.
  • Aeroplane, Car, Ship (subclasses): each adds specific data/behavior.
    • Aeroplane: commercial/private details
    • Car: electric/non-electric details
    • Ship: cargo capacity details

This avoids rewriting the same shared code multiple times.

UML is-a Relationship

Inheritance is modeled as an is-a relation:

  • Aeroplane is a Vehicle
  • Car is a Vehicle
  • Ship is a Vehicle
Vehicle
  ^
  |-- Aeroplane
  |-- Car
  |-- Ship

Why Inheritance Is Useful

AdvantageSummary
Code reuseMultiple subclasses reuse superclass code/properties
EfficiencyCommon code is written once
Simpler maintenanceChange superclass once; reflected in subclasses
ModularityInherited structures are easier to reuse in other apps

Access Modifiers in Inheritance (Visibility Rules)

When using inheritance, modifier choice controls which classes can access variables/methods.

ModifierVisible where?Key point
privateOnly in declaring classNot directly visible in subclass
protectedSuperclass + subclassesHidden from unrelated external classes
publicEverywhereAccessible inside and outside hierarchy
default (package)Same package onlyNot visible outside package

Python Examples (Inheritance)

1. Basic Inheritance

class Vehicle:
    def __init__(self, brand: str):
        self.brand = brand

    def move(self) -> str:
        return "Moving..."


class Car(Vehicle):
    def __init__(self, brand: str):
        super().__init__(brand)

    def honk(self) -> str:
        return "Beep beep!"


car = Car("Toyota")
print(car.brand)   # Toyota
print(car.move())  # Moving...
print(car.honk())  # Beep beep!

2. Method Overriding (Polymorphism)

class Animal:
    def speak(self) -> str:
        return "Some sound"


class Dog(Animal):
    def speak(self) -> str:
        return "Woof"


class Cat(Animal):
    def speak(self) -> str:
        return "Meow"


for animal in [Dog(), Cat(), Animal()]:
    print(animal.speak())
# Woof
# Meow
# Some sound

3. Reusing Parent Constructor with super()

class Person:
    def __init__(self, name: str):
        self.name = name


class Student(Person):
    def __init__(self, name: str, grade: int):
        super().__init__(name)  # Initialize inherited fields
        self.grade = grade


student = Student("Ava", 11)
print(student.name, student.grade)  # Ava 11

Start typing to search all published objectives.