Sobes.tech
Middle

When does method overriding occur?

sobes.tech AI

Answer from AI

Method overriding in object-oriented programming occurs when a subclass has a method with the same name, parameter list (or signature), and return type as a method in its parent class. This allows the subclass to provide its own implementation of the inherited method from the parent.

Main conditions for overriding:

  • Inheritance: The subclass must inherit from the parent class.
  • Method signature: The method being overridden in the subclass must have the same signature (method name and parameter types, their order, and quantity) as the method in the parent class. In some languages (e.g., Java), matching the return type or its covariance is also required.
  • Access modifiers: The access modifier of the overridden method in the subclass cannot be more restrictive than that in the parent class.
  • Methods that cannot be overridden: Static (static), final (final in Java, sealed in C#), and private (private) methods, as they do not participate in polymorphism through inheritance.

Example in Java:

// Parent class
class Animal {
    public void sound() {
        // Default implementation
        System.out.println("Animal makes a sound");
    }
}

// Subclass overriding the sound() method
class Dog extends Animal {
    @Override // Annotation for compiler check
    public void sound() {
        // Specific implementation for Dog
        System.out.println("Dog barks");
    }
}

class Main {
    public static void main(String[] args) {
        Animal myAnimal = new Animal();
        Animal myDogAsAnimal = new Dog(); // Polymorphism
        Dog myDog = new Dog();

        myAnimal.sound();      // Calls sound() from Animal
        myDogAsAnimal.sound(); // Calls overridden sound() from Dog (thanks to polymorphism)
        myDog.sound();         // Calls overridden sound() from Dog
    }
}

Example in Python:

# Parent class
class Animal:
    def sound(self):
        # Default implementation
        print("Animal makes a sound")

# Subclass overriding the sound() method
class Dog(Animal):
    def sound(self):
        # Specific implementation for Dog
        print("Dog barks")

# Usage
my_animal = Animal()
my_dog_as_animal = Dog() # Polymorphism
my_dog = Dog()

my_animal.sound()       # Calls sound() from Animal
my_dog_as_animal.sound()  # Calls overridden sound() from Dog (thanks to polymorphism)
my_dog.sound()          # Calls overridden sound() from Dog

Overriding is used to achieve runtime polymorphism, allowing different actions to be performed depending on the actual object type, despite using a reference to the parent class. This is a key principle of OOP for building flexible and extensible systems.