Method overriding lets a child object change how a method works from its parent. This helps customize behavior while keeping the same method name.
0
0
Method overriding in Javascript
Introduction
When you want a child object to do something different than the parent for the same action.
When you have a general method in a parent and need specific versions in children.
When you want to reuse code but change small parts in child objects.
When building games where different characters act differently but share common actions.
When creating UI components that share a base but behave uniquely.
Syntax
Javascript
class Parent { methodName() { // parent method code } } class Child extends Parent { methodName() { // child method code overrides parent } }
The child class uses the same method name to replace the parent's method.
Use extends to create a child class from a parent class.
Examples
The
Dog class changes the speak method to bark instead of the generic animal sound.Javascript
class Animal { speak() { console.log('Animal speaks'); } } class Dog extends Animal { speak() { console.log('Dog barks'); } }
The
Car class overrides start to show a specific message.Javascript
class Vehicle { start() { console.log('Vehicle starting'); } } class Car extends Vehicle { start() { console.log('Car engine starting'); } }
Sample Program
This program shows method overriding. The Student class changes the greet method from Person. When we call greet on each, they print different messages.
Javascript
class Person { greet() { console.log('Hello from Person'); } } class Student extends Person { greet() { console.log('Hello from Student'); } } const person = new Person(); const student = new Student(); person.greet(); student.greet();
OutputSuccess
Important Notes
Overriding only works if the method name is exactly the same in parent and child.
You can call the parent's method inside the child using super.methodName() if needed.
Summary
Method overriding lets child classes change parent methods.
Use the same method name in child to replace parent behavior.
It helps customize shared actions for different objects.