Junior
When does method overriding occur in programming?
sobes.tech AI
Answer from AI
Method overriding occurs in inheritance, when a child class provides its own implementation of a method that is already defined in the parent class. The method signature (name, return type, and number/type of arguments) must match that of the parent class method. This allows polymorphism to work: an object of the child class, used as a parent object, calls its specific method implementation.
Examples of usage:
- Changing the logic of inherited behavior.
- Providing a subclass-specific implementation of a common interface.
Key points:
- An is-a relationship (inheritance) is required.
- The method signature must match.
- The access modifier can be the same or less restrictive than that of the parent method.
finalorstaticmethods cannot be overridden (in most languages).
// Example in Java
class Animal {
public void makeSound() {
System.out.println("Generic animal sound");
}
}
class Dog extends Animal {
@Override // Annotation indicating override
public void makeSound() {
System.out.println("Woof!");
}
}
// Usage
// Animal myAnimal = new Animal();
// myAnimal.makeSound(); // Output: Generic animal sound
//
// Animal myDog = new Dog();
// myDog.makeSound(); // Output: Woof! (calls the overridden method)
# Example in Python
class Animal:
def make_sound(self):
print("Generic animal sound")
class Dog(Animal):
def make_sound(self): # Method override
print("Woof!")
# Usage
# animal = Animal()
# animal.make_sound() # Output: Generic animal sound
#
# dog = Dog()
# dog.make_sound() # Output: Woof!