Junior
When does method overriding occur?
sobes.tech AI
Answer from AI
Method overriding occurs in an inheritance hierarchy when a subclass provides its own implementation of a method that is already defined in the parent class with the same name, signature (matching parameter types and count), and return type (or covariant in the case of return object type).
Key characteristics:
- Inheritance: Overriding is only possible within the context of inheritance (parent and child classes).
- Signature: The method in the subclass must have the same signature (name, number, and types of parameters) and return type (or its covariant subtype) as the method in the parent class.
- Accessibility: The method being overridden must be accessible to the subclass (usually
public,protected). - Polymorphism: Overriding is the basis of runtime polymorphism, allowing objects of the subclass to respond to method calls in their own way, even when accessed through a parent class reference.
Example (Java):
// Parent class
class Animal {
// Method to be overridden
public void makeSound() {
System.out.println("Animal makes a sound");
}
}
// Child class
class Dog extends Animal {
// Overriding makeSound() method
@Override // The @Override annotation is optional but recommended
public void makeSound() {
System.out.println("Dog barks");
}
}
Usage example:
// Create a Dog object
Animal myDog = new Dog();
// Call the method. The overridden version from Dog will be invoked
myDog.makeSound(); // Output: Dog barks
// Create an Animal object
Animal someAnimal = new Animal();
// Call the method. The version from Animal will be invoked
someAnimal.makeSound(); // Output: Animal makes a sound