Sobes.tech
Junior — Middle

Can you explain the concept of method overriding in object-oriented programming?

sobes.tech AI

Answer from AI

Method overriding in object-oriented programming is the ability of a subclass to define its own version of a method that is already declared in the base class. This allows changing or extending the behavior of the method for subclass objects.

In Python, overriding simply occurs by defining a method with the same name in the child class:

class Animal:
    def speak(self):
        print("Animal makes a sound")

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

animal = Animal()
animal.speak()  # Animal makes a sound

dog = Dog()
dog.speak()     # Woof

Here, the speak method in the Dog class overrides the method from Animal. When calling speak on a Dog object, the overridden method is used.

This is a key mechanism for implementing polymorphism, allowing objects of different classes to behave differently when the same method is called.