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.
Hierarchical inheritance is useful for:
Let’s explore a practical example to understand hierarchical inheritance better.
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")
class Dog(Animal):
def bark(self):
print(f"{self.name} says Woof!")
class Cat(Animal):
def meow(self):
print(f"{self.name} says Meow!")
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!
Animal:
__init__ method initializes the name attribute.Dog:
name attribute, eat method, and sleep method from the Animal class.Dog that prints a barking sound.Cat:
name attribute, eat method, and sleep method from the Animal class.Cat that prints a meowing sound.