Sobes.tech
Junior — Middle

Does the use of inheritance necessarily imply support for polymorphism in object-oriented programming?

sobes.tech AI

Answer from AI

Inheritance by itself does not necessarily imply support for polymorphism, but it is often used together with it. Inheritance is a mechanism that allows creating a new class based on an existing one, inheriting its properties and methods.

Polymorphism, on the other hand, is the ability of objects of different classes to respond to the same messages (method calls) in different ways. For polymorphism, it is important that methods are overridden in subclasses.

Thus, inheritance creates a structure for polymorphism, but if methods are not overridden and not used through references to the base class, polymorphism does not manifest.

Example:

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

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

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

animals = [Dog(), Cat()]
for animal in animals:
    animal.speak()  # Polymorphic call