Junior — Middle
Can you explain what method overriding means in object-oriented programming and how it is applied?
sobes.tech AI
Answer from AI
Method overriding is a feature in object-oriented programming where a subclass provides its own implementation of a method that is already defined in its superclass.
This allows changing or extending the behavior of the method for a specific subclass while maintaining a common interface.
Example in JavaScript (Node.js):
class Animal {
speak() {
console.log('Animal makes a sound');
}
}
class Dog extends Animal {
speak() {
console.log('Dog barks');
}
}
const dog = new Dog();
dog.speak(); // Outputs: Dog barks
Here, the speak method in the Dog class overrides the method from the Animal class to provide more specific behavior.