Method Overriding
Last updated
Last updated
Method overriding in JavaScript involves redefining a method in a child class that was already defined in its parent class.
This allows the child class to provide a specific implementation of the method while inheriting the rest of the parent class's behavior.
In this example:
The Animal
class has a method speak()
that returns a generic string.
The Dog
class extends Animal
and overrides the speak()
method to return "Dog barks".
The Cat
class extends Animal
and overrides the speak()
method to return "Cat meows".
When you create instances of Animal
, Dog
, and Cat
and call the speak()
method on each instance:
For the Animal
instance, it invokes the speak()
method from the parent class returning "Animal speaks".
For the Dog
instance, it invokes the overridden speak()
method in the Dog
class returning "Dog barks".
For the Cat
instance, it invokes the overridden speak()
method in the Cat
class returning "Cat meows".
This demonstrates how method overriding works in JavaScript, allowing child classes to provide their own implementation of methods defined in their parent classes.