Inheritance (OOP) (OCR A-Level Computer Science): Revision Notes
Inheritance (OOP)
Overview
Inheritance is a key principle of Object-Oriented Programming (OOP) that enables a new class to inherit attributes and methods from an existing class. The main purpose of inheritance is to promote code reuse and hierarchical relationships between classes, which helps organise and simplify code. With inheritance, programmers can create specialised classes based on more general classes, building on existing functionality without duplicating code.
Key Concepts of Inheritance
Parent and Child Classes
- The parent class (also called the superclass or base class) is the existing class from which attributes and methods are inherited.
- The child class (also known as the subclass or derived class) inherits attributes and methods from the parent class but can also have its own unique attributes and methods.
Example:
class Animal: # Parent class
def speak(self):
print("The animal makes a sound.")
class Dog(Animal): # Child class
pass
Here, Animal is the parent class, and Dog is a child class that inherits from Animal. Although Dog has no methods defined in it, it inherits speak from Animal.
Purpose of Inheritance
- Code Reuse: Inheritance allows child classes to use the attributes and methods of the parent class without rewriting the code, saving time and reducing duplication.
- Hierarchy and Specialisation: Inheritance enables the creation of a class hierarchy, where general classes can be extended into more specific ones. This models real-world relationships, making the code easier to understand and maintain.
- Extendability: By building on an existing class, child classes can add or override methods, allowing programmers to extend and customise functionality as needed.
Inheritance in Action
In Python, inheritance is established by passing the parent class as a parameter to the child class.
Example:
class Dog(Animal): # Dog inherits from Animal
def bark(self):
print("Woof woof!")
Here, Dog inherits everything from Animal but also has its own unique method, bark.
Method Overriding
Definition: Method overriding occurs when a child class provides a new implementation for a method that is already defined in the parent class. This allows the child class to modify or specialise the behaviour of an inherited method.
Example:
class Animal:
def speak(self):
print("The animal makes a sound.")
class Dog(Animal):
def speak(self): # Overriding speak method
print("Woof woof!")
In this example, Dog has its own version of speak, which overrides the speak method of the Animal class.
Using super()
Purpose: The super() function allows the child class to access methods or attributes from the parent class. This is especially useful when a child class overrides a method but still needs to use functionality from the parent class's version of that method.
Example:
class Animal:
def __init__(self, species):
self.species = species
class Dog(Animal):
def __init__(self, species, breed):
super().__init__(species) # Calls the parent class's constructor
self.breed = breed
In this example, super().init(species) calls the init method from Animal, ensuring that the species attribute is correctly initialised.
Example: Animal Inheritance Hierarchy
Below is an example demonstrating inheritance in an animal class hierarchy, where Animal is a general parent class, and Dog and Cat are more specific child classes.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "The animal makes a sound."
class Dog(Animal):
def speak(self): # Overriding speak method
return "Woof woof!"
class Cat(Animal):
def speak(self): # Overriding speak method
return "Meow!"
# Creating instances of each class
animal = Animal("Generic Animal")
dog = Dog("Buddy")
cat = Cat("Whiskers")
# Using inherited and overridden methods
print(animal.speak()) # Outputs: The animal makes a sound.
print(dog.speak()) # Outputs: Woof woof!
print(cat.speak()) # Outputs: Meow!
Explanation of the Example
- Parent Class (Animal): Defines a speak method and an attribute name.
- Child Class (Dog and Cat): Inherit the name attribute from Animal and override the speak method to provide species-specific sounds.
Benefits of Inheritance
- Code Reusability: Shared behaviour in the parent class can be reused by all child classes, reducing code redundancy.
- Extensibility: Inheritance allows child classes to extend or customise behaviours, making it easy to add new functionalities without modifying the parent class.
- Hierarchical Organisation: Class hierarchies mirror real-world relationships, which makes code organisation and readability clearer.
Note Summary
Common Mistakes with Inheritance
- Overusing Inheritance: Not all relationships require inheritance. Sometimes, composition (using objects within other objects) is a better approach if there's no strong "is-a" relationship.
- Forgetting super() in Overridden Methods: When overriding methods, forgetting to call super() can lead to incomplete initialisation or missed functionality from the parent class.
- Directly Accessing Parent Methods: Using the parent class name to access parent methods directly (e.g., ParentClass.method()) instead of super() can make code harder to maintain.
Key Takeaways
- Inheritance allows a class (child) to inherit attributes and methods from another class (parent), promoting code reuse.
- Overriding lets child classes provide specific implementations of parent class methods.
- super() enables child classes to access and build on parent class functionality, ensuring complete and consistent initialisation and behaviour.
- Inheritance provides a structured, efficient way to model hierarchical relationships and reduce code duplication in OOP.