Introduction to OOP with Multiple Classes
At the HL level, Object-Oriented Programming extends beyond single classes to encompass rich relationships between multiple classes. Understanding how classes interact, inherit from one another, and collaborate is essential for designing real-world software systems.
The core concepts covered in B3.2 are:
- Inheritance , creating new classes based on existing ones
- Polymorphism , allowing objects to take on multiple forms
- Abstract classes , blueprints that cannot be instantiated directly
- Composition & Aggregation , modelling "has-a" relationships between classes
- Design Patterns , reusable solutions to common software design problems
These concepts work together to make code more modular, reusable, and maintainable , the hallmarks of well-engineered software.
IB HL Computer Science expects you to not only understand these concepts theoretically but also to apply them in code (Java or Python) and reason about design decisions using them.
Inheritance
Inheritance: A mechanism in OOP where a subclass (child class) derives attributes and methods from a superclass (parent class), enabling code reuse and the modelling of hierarchical relationships.
Inheritance allows a child class to:
- Access all public and protected methods and attributes of the parent
- Override existing methods to provide specialised behaviour
- Add new methods and attributes unique to the subclass
Think of it as a family tree: a Dog class can inherit from an Animal class, gaining generic animal behaviour while also defining dog-specific behaviour.
Python , Inheritance in action:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Some generic sound"
class Dog(Animal): # Dog inherits from Animal
def speak(self): # Override the speak method
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
d = Dog("Rex")
print(d.name) # Rex (inherited attribute)
print(d.speak()) # Woof! (overridden method)
Here, Dog and Cat both inherit name from Animal but each overrides speak() with their own implementation.
Use inheritance when there is a clear "is-a" relationship: a Dog is an Animal. If the relationship is "has-a", use composition or aggregation instead.
Students often apply inheritance too broadly. Not every relationship between classes warrants inheritance , overusing it leads to tightly coupled, fragile code. Always ask: "Is this truly an is-a relationship?"
