Hierarchical inheritance

Hierarchical inheritance is a type of inheritance in object-oriented programming where multiple classes inherit from a single base class. This structure allows multiple derived classes to share the properties and methods of a common parent class, promoting code reusability and consistency.

Key Concepts of Hierarchical Inheritance

  1. Base Class (Parent Class): The class whose properties and methods are inherited by multiple derived classes.
  2. Derived Classes (Child Classes): Classes that inherit properties and methods from the base class.

Why Use Hierarchical Inheritance?

Hierarchical inheritance is useful for:

  • Code Reusability: Sharing common code across multiple classes.
  • Consistency: Ensuring consistent behavior across different classes.
  • Simplified Maintenance: Easier to update shared functionality in one place.

Example of Hierarchical Inheritance in Python

Let’s explore a practical example to understand hierarchical inheritance better.

Step 1: Define the Base Class

class Animal:
    def __init__(self, name):
        self.name = name
    
    def eat(self):
        print(f"{self.name} is eating")
    
    def sleep(self):
        print(f"{self.name} is sleeping")

Step 2: Define the Derived Classes

class Dog(Animal):
    def bark(self):
        print(f"{self.name} says Woof!")

class Cat(Animal):
    def meow(self):
        print(f"{self.name} says Meow!")

Step 3: Instantiate and Use the Derived Classes

if __name__ == "__main__":
    my_dog = Dog("Buddy")
    my_cat = Cat("Whiskers")

    # Using methods from the base class
    my_dog.eat()  # Output: Buddy is eating
    my_cat.sleep()  # Output: Whiskers is sleeping

    # Using methods from the derived classes
    my_dog.bark()  # Output: Buddy says Woof!
    my_cat.meow()  # Output: Whiskers says Meow!

Detailed Breakdown

  1. Base Class Animal:
    • Initialization: The __init__ method initializes the name attribute.
    • eat Method: Prints a message indicating the animal is eating.
    • sleep Method: Prints a message indicating the animal is sleeping.
  2. Derived Class Dog:
    • Inherits the name attribute, eat method, and sleep method from the Animal class.
    • bark Method: Adds a new method specific to Dog that prints a barking sound.
  3. Derived Class Cat:
    • Inherits the name attribute, eat method, and sleep method from the Animal class.
    • meow Method: Adds a new method specific to Cat that prints a meowing sound.