OOP: Inheritance and Polymorphism

Learn about inheritance and polymorphism, key concepts in object-oriented programming.


OOP: Inheritance and Polymorphism in Python

Learn about inheritance and polymorphism, key concepts in object-oriented programming.

Inheritance

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows you to create new classes based on existing classes. The new class, known as the child class or subclass, inherits properties (attributes) and behaviors (methods) from the existing class, known as the parent class or superclass. This promotes code reusability and establishes an "is-a" relationship between classes.

Key Aspects of Inheritance:

  • Code Reusability: Avoids writing the same code repeatedly.
  • Organization: Creates a hierarchical structure, making code easier to understand and maintain.
  • Extensibility: Allows you to add new features to existing classes without modifying the original code.

Python Example:

 class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print("Generic animal sound")

class Dog(Animal):  # Dog inherits from Animal
    def speak(self):
        print("Woof!")

class Cat(Animal):  # Cat also inherits from Animal
    def speak(self):
        print("Meow!")


my_dog = Dog("Buddy")
my_cat = Cat("Whiskers")

my_dog.speak()  # Output: Woof!
my_cat.speak()  # Output: Meow!
print(my_dog.name) # Output: Buddy - Inherited from Animal 

In this example, `Dog` and `Cat` inherit from `Animal`. They inherit the `name` attribute and the `speak` method. Each child class *overrides* the `speak` method to provide its own specific implementation.

Polymorphism

Polymorphism, meaning "many forms," is the ability of an object to take on many forms. In OOP, it refers to the ability of a single function or method to work with objects of different classes. There are two main types of polymorphism: *overriding* and *overloading*.

Key Aspects of Polymorphism:

  • Flexibility: Write code that can work with different types of objects.
  • Maintainability: Changes to one class are less likely to break code that uses other classes.
  • Abstraction: Focus on the common interface rather than the specific implementation.

Overriding (Runtime Polymorphism):

This is the type of polymorphism demonstrated in the inheritance example above. A subclass provides a specific implementation of a method that is already defined in its parent class.

Overloading (Compile-time Polymorphism - Limited in Python):

Overloading involves defining multiple methods with the same name but different parameters. Python doesn't directly support traditional overloading (like in Java or C++). However, you can achieve similar results using default arguments and variable-length argument lists.

Python Example (Overriding):

 class Animal:
    def speak(self):
        print("Generic animal sound")

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

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

def animal_sound(animal):  #This function demonstrate polymorphism
    animal.speak()

my_dog = Dog()
my_cat = Cat()

animal_sound(my_dog)  # Output: Woof!
animal_sound(my_cat)  # Output: Meow! 

The `animal_sound` function can accept either a `Dog` or a `Cat` object (or any other object that inherits from `Animal` and implements the `speak` method) and call its `speak` method. The correct `speak` method is called based on the actual type of the object passed to the function. This is polymorphism in action.

Python Example (Simulating Overloading with Default Arguments):

 class Calculator:
    def add(self, x, y=None, z=None):
        if y is None and z is None:
            return x
        elif z is None:
            return x + y
        else:
            return x + y + z

calc = Calculator()
print(calc.add(5))       # Output: 5
print(calc.add(5, 3))    # Output: 8
print(calc.add(5, 3, 2)) # Output: 10 

This example demonstrates a way to simulate overloading using default arguments. The `add` method can take one, two, or three arguments, and it behaves differently depending on how many arguments are provided.

Conclusion

Inheritance and Polymorphism are powerful tools in object-oriented programming. They promote code reuse, organization, and flexibility, leading to more maintainable and scalable software.