Inheritance lets a child class reuse and extend the behavior of a parent class.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound.`;
}
toString() {
return `Animal(${this.name})`;
}
}
class Dog extends Animal {
speak() {
return `${this.name} barks.`;
}
}
class Cat extends Animal {
speak() {
return `${this.name} meows.`;
}
}
const dog = new Dog("Rex");
dog.speak(); // "Rex barks."
dog.toString(); // "Animal(Rex)" — inherited from Animal
superclass Employee extends Person {
constructor(name, age, company) {
super(name, age); // calls Person's constructor
this.company = company;
}
introduce() {
return `${super.introduce()} I work at ${this.company}.`;
}
}
instanceof checkdog instanceof Dog; // true
dog instanceof Animal; // true — Dog IS an Animal
dog instanceof Cat; // false
Shape with:
(color = "black").area() — returns 0 (to be overridden).toString() — returns "Shape(color: black)".Circle extends Shape with:
(radius, color) — calls super(color).area() — returns Math.PI * radius² rounded to 2 decimal places.toString() — returns "Circle(radius: 5, color: red, area: 78.54)".Rectangle extends Shape with:
(width, height, color).area() — returns width * height.toString() — returns "Rectangle(4×6, color: blue, area: 24)".#output: both toString() values joined with " | ".Use extends to inherit: class Child extends Parent {}