Method overriding is a concept in JavaScript (as well as in other object-oriented programming languages) where a subclass provides a specific implementation for a method that is already defined in its superclass (parent class). This allows the subclass to customize the behavior of the inherited method while keeping the method name and interface the same.
Here's an example of method overriding in JavaScript:
class Animal {
speak() {
return "Animal makes a sound";
}
}
class Dog extends Animal {
speak() {
return "Dog barks";
}
}
class Cat extends Animal {
speak() {
return "Cat meows";
}
}
const genericAnimal = new Animal();
const dog = new Dog();
const cat = new Cat();
console.log(genericAnimal.speak()); // Outputs: "Animal makes a sound"
console.log(dog.speak()); // Outputs: "Dog barks"
console.log(cat.speak()); // Outputs: "Cat meows"
In this example:
We have a base class Animal with a speak method that returns a generic message.
We then have two subclasses, Dog and Cat, which both inherit from the
Animal class and override the speak method to provide their own unique behavior.
When we create instances of Animal, Dog, and
Cat, and call the speak method on them, we get different responses based on the overridden methods.
Method overriding is useful when you want to provide specialized behavior for specific subclasses while still maintaining a consistent interface across all instances of those subclasses. It allows you to build upon and extend the functionality of a parent class in a flexible and organized manner.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Method overriding is a concept in JavaScript (as well as in other object-oriented programming languages) where a subclass provides a specific implementation for a method that is already defined in its superclass (parent class). This allows the subclass to customize the behavior of the inherited method while keeping the method name and interface the same.
Here's an example of method overriding in JavaScript:
In this example:
We have a base class Animal with a speak method that returns a generic message.
We then have two subclasses, Dog and Cat, which both inherit from the Animal class and override the speak method to provide their own unique behavior.
When we create instances of Animal, Dog, and Cat, and call the speak method on them, we get different responses based on the overridden methods.
Method overriding is useful when you want to provide specialized behavior for specific subclasses while still maintaining a consistent interface across all instances of those subclasses. It allows you to build upon and extend the functionality of a parent class in a flexible and organized manner.