Class inheritance is a fundamental concept in object-oriented programming that allows a class to inherit properties and methods from another class. In JavaScript, class inheritance is implemented using the extends
keyword.
Class inheritance allows a subclass to inherit properties and methods from a superclass. This means that the subclass can reuse code from the superclass, which can save time and effort in development. The subclass can also add its own properties and methods, or override those of the superclass.
Let's take a look at an example:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
let dog = new Dog('Rufus');
dog.speak(); // Output: "Rufus barks."
In this example, we have a superclass called Animal
and a subclass called Dog
. The Dog
class extends the Animal
class using the extends
keyword. This means that the Dog
class inherits the name
property and speak()
method from the Animal
class.
The Dog
class also overrides the speak()
method of the Animal
class with its own implementation. When we create a new instance of the Dog
class and call the speak()
method, it outputs "Rufus barks."
We can also call the speak()
method of the Animal
class on an instance of the Dog
class:
let animal = new Animal('Generic Animal');
animal.speak(); // Output: "Generic Animal makes a noise."
dog.speak(); // Output: "Rufus barks."
In this example, we create a new instance of the Animal
class and call its speak()
method. It outputs "Generic Animal makes a noise." We then call the speak()
method of the Dog
class on the dog
instance, which outputs "Rufus barks."
This demonstrates how class inheritance allows a subclass to inherit properties and methods from a superclass, and how the subclass can override or add its own properties and methods.
Class inheritance is a powerful concept in object-oriented programming that allows classes to reuse code from other classes. In JavaScript, class inheritance is implemented using the extends
keyword. This allows a subclass to inherit properties and methods from a superclass, and to override or add its own properties and methods.