Inheritance in classes
Course: Promises and async, await - chapter 3
Inheritance in JavaScript classes allows one class to inherit properties and methods from another class. This mechanism enables code reuse, making it easier to create new classes that are based on existing ones, without having to duplicate code.
Assignment #1 - Create a Circle class
Section titled “Assignment #1 - Create a Circle class”class Circle { constructor(radius, color) { this.radius = radius; this.color = color; }
area() { const area = this.radius * this.radius * Math.PI; return area; }
paint() { console.log(`Painting with color ${this.color}`); }
}
const circle = new Circle(2, "red")const area = circle.area();console.log(area)💡 Can you see there is code repetition here and in the Rectangle class?
Assignment #2 - Create a base shape class
Section titled “Assignment #2 - Create a base shape class”Base class
Section titled “Base class”class Shape { constructor(color) { this.color = color; }
paint() { console.log(`Painting with color ${this.color}`); }
area() { throw new Error('The area method must be implemented in the subclass'); }
getDescription() { return `A shape with color ${this.color}`; }}Rectangle class
Section titled “Rectangle class”class Rectangle extends Shape { constructor(width, height, color) { super(color); // Call the parent class constructor to set the color this.width = width; this.height = height; }
area() { return this.width * this.height; }
getDescription() { return `A rectangle with width ${this.width}, height ${this.height}, and color ${this.color}`; }}Circle class
Section titled “Circle class”class Circle extends Shape { constructor(radius, color) { super(color); // Call the parent class constructor to set the color this.radius = radius; }
area() { return Math.PI * this.radius * this.radius; }
getDescription() { return `A circle with radius ${this.radius} and color ${this.color}`; }}Try playing with it
Section titled “Try playing with it”const circle = new Circle(20);console.log(circle.area());