Inheritance allows one class to inherit properties and methods from another class. The extends keyword is used to create a class as a child of another class.
helloworld.js
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const animal = new Animal('Jimbu');
animal.speak();
const dog = new Dog('Marx');
dog.speak();
Output
Jimbu makes a sound. Marx barks.
animal.speak()
This calls the speak() method of the Animal class, which prints "Jimbu makes a sound.".
dog.speak()
This calls the overridden speak() method of the Dog class, which prints "Marx barks.".
Inheritance allows you to reuse code from a parent class in a child class. In this example, the Dog class inherits the name property and could inherit other methods from Animal if they existed. This reduces code duplication, as common functionality is written once in the parent class.
Previous Next Home
No comments:
Post a Comment