About Lesson
Inheritance in JavaScript
Inheritance allows creating a subclass that inherits properties and methods from a parent class. This enables code reuse and the creation of specialized versions of classes.
Example: Inheritance with Animal and Dog Classes
JavaScript
class Animal {
constructor(name) {
this.name = name;
}
makeSound() {
console.log(`${this.name} makes a sound.`);
}
}
// Dog extends Animal
class Dog extends Animal {
constructor(name, breed) {
super(name); // Calls the parent class constructor
this.breed = breed;
}
makeSound() {
console.log(`${this.name} barks.`);
}
}
const myDog = new Dog("Buddy", "Golden Retriever");
myDog.makeSound(); // Output: Buddy barks.
In this example:
- Animal is a base class with a makeSound method.
- Dog is a subclass of Animal that overrides makeSound to provide a specific behavior for dogs.