INHERITANCE AND POLYMORPHISM
Inheritance and polymorphism are two important concepts in Object-Oriented Programming (OOP) that facilitate code reuse and flexibility in designing and implementing software systems.
1. Inheritance: Inheritance is a mechanism in which a new class (subclass or derived class) is created based on an existing class (superclass or base class). The subclass inherits the attributes and methods of the superclass, allowing you to reuse code and create a hierarchical relationship between classes.
The subclass can extend the behavior of the superclass by adding new attributes or methods, or it can override existing methods to provide specialized implementations.
Example:
# Base class (superclass)
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
pass
# Derived class (subclass)
class Dog(Animal):
def make_sound(self):
return "Woof!"
# Derived class (subclass)
class Cat(Animal):
def make_sound(self):
return "Meow!"
# Creating objects
dog = Dog("Buddy")
cat = Cat("Whiskers")
# Calling the overridden method
print(dog.make_sound()) # Output: Woof!
print(cat.make_sound()) # Output: Meow!
In this example, the Dog
and Cat
classes inherit from the Animal
class. Both Dog
and Cat
classes override the make_sound()
method to provide specialized implementations.
2. Polymorphism: Polymorphism is the ability of objects of different classes to be treated as objects of a common superclass. It allows a single interface to represent different types of objects. Polymorphism simplifies code by allowing you to write code that can work with objects of multiple classes, as long as they share a common interface (i.e., same methods or attributes).
Polymorphism is achieved through method overriding, as shown in the example above. When you call the make_sound()
method on dog
and cat
objects, the appropriate method is dynamically chosen based on the object's actual type (i.e., Dog or Cat).
Example:
# A function that accepts an Animal object and calls its make_sound method
def animal_sound(animal):
return animal.make_sound()
# Using the function with different types of objects
print(animal_sound(dog)) # Output: Woof!
print(animal_sound(cat)) # Output: Meow!
In this example, the animal_sound()
function accepts an Animal
object and calls its make_sound()
method. It can be used with both Dog
and Cat
objects because of polymorphism.
In conclusion, inheritance and polymorphism are powerful concepts in OOP that promote code reuse, extensibility, and flexibility. Inheritance allows you to create hierarchical relationships between classes, while polymorphism enables you to work with objects of different classes through a common interface. Together, these concepts enhance the modularity and maintainability of your code.