Inheritance
Inheritance in JavaScript allows a class to inherit properties and methods from another class. This is done using the extends keyword. Here’s an example to illustrate how inheritance works in JavaScript:
Basic Example of Inheritance
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // Calls the constructor of the parent class (Animal)
this.breed = breed;
}
speak() {
super.speak(); // Calls the speak method of the parent class
console.log(`${this.name} barks.`);
}
getBreed() {
console.log(`${this.name} is a ${this.breed}.`);
}
}
// Creating an instance of the Dog class
const myDog = new Dog('Buddy', 'Golden Retriever');
// Calling methods
myDog.speak(); // Outputs: "Buddy makes a sound." followed by "Buddy barks."
myDog.getBreed(); // Outputs: "Buddy is a Golden Retriever."
Explanation
Animal Class: This is the parent class with a constructor that initializes the name property and a method speak that logs a message.
Dog Class: This class inherits from the Animal class using the extends keyword. It has its own constructor that calls the parent class constructor using super(name), and it also initializes an additional property breed.
Method Overriding: The speak method in the Dog class calls the speak method of the parent class using super.speak() and then adds additional behavior.
Creating an Instance: An instance of the Dog class is created with the name 'Buddy' and breed 'Golden Retriever'. Methods speak and getBreed are called on this instance.
Points to Note
- The super keyword is used to call the constructor and methods of the parent class.
- You can override methods in the child class and still call the parent class methods using super.methodName().
- Inheritance allows the creation of a hierarchy of classes, making code reusable and easier to manage.
This example demonstrates the basic principles of inheritance in JavaScript, showing how a class can extend another class, inherit its properties and methods, and override or add new functionality.