Junior
What is overriding in programming?
sobes.tech AI
Answer from AI
Overriding is an object-oriented programming mechanism that allows a subclass (child class) to provide its own specific implementation of a method that is already defined in its superclass (parent class).
Main characteristics of overriding:
- Method signature: The overriding method in the subclass must have the same signature (method name and parameter list) and the same return type (or covariant type) as the method in the superclass.
- Inheritance: Overriding is only possible within inheritance hierarchies.
- Polymorphism: Overriding is one of the key mechanisms for implementing polymorphism at runtime. It means that the specific method called is determined by the object's type at runtime, not the reference type.
- Visibility: The overriding method cannot have a more restrictive access modifier than the method in the superclass.
Example:
// Superclass
class Animal {
public void makeSound() {
// General implementation
System.out.println("Any animal sound");
}
}
// Subclass
class Dog extends Animal {
// Overriding makeSound()
@Override // The @Override annotation is not mandatory but good practice
public void makeSound() {
// Specific implementation for Dog
System.out.println("Woof!");
}
}
// Usage
class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myDogAsAnimal = new Dog(); // Polymorphic reference
Dog myDog = new Dog();
myAnimal.makeSound(); // Calls Animal.makeSound() -> Any animal sound
myDogAsAnimal.makeSound(); // Calls Dog.makeSound() (thanks to overriding and polymorphism) -> Woof!
myDog.makeSound(); // Calls Dog.makeSound() -> Woof!
}
}