Polymorphism with Inheritance

Polymorphism with inheritance allows objects of different classes to be treated as objects of a common superclass. This enables a unified interface for different class types, promoting flexibility and code reusability.

Key Concepts

  1. Method Overriding: Subclasses provide specific implementations for methods defined in the superclass.
  2. Common Interface: Different classes share a method signature but have their own implementations.
  3. Dynamic Method Resolution: The method called is determined at runtime based on the object’s type.

Example of Polymorphism with Inheritance

Base Class and Derived Classes

class Animal:
    def speak(self):
        return "Some sound"

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

Using Polymorphism

def animal_sound(animal):
    print(animal.speak())

# Instances
dog = Dog()
cat = Cat()

# Polymorphic behavior
animal_sound(dog)  # Output: Woof!
animal_sound(cat)  # Output: Meow!

How It Works

  • Base Class (Animal): Defines a generic speak method.
  • Derived Classes (Dog, Cat): Override the speak method with specific implementations.
  • Polymorphic Function (animal_sound): Accepts any Animal type and calls the speak method, demonstrating polymorphism.

Example: Shapes with Polymorphism

class Shape:
    def area(self):
        raise NotImplementedError("Subclass must implement abstract method")

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius ** 2

class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side ** 2

# Polymorphic function
def print_area(shape):
    print(f"Area: {shape.area()}")

# Instances
circle = Circle(5)
square = Square(4)

# Polymorphic behavior
print_area(circle)  # Output: Area: 78.5
print_area(square)  # Output: Area: 16

Key Points

  • Base Class (Shape): Abstract method area is defined.
  • Derived Classes (Circle, Square): Implement the area method with specific calculations.
  • Polymorphic Function (print_area): Accepts any Shape type and calls area.