Careeroza
Inheritance
extends and super
Example
A subclass inherits everything from its parent. super(...) calls the parent constructor; super.method() calls a parent method:
class Employee {
constructor(name, salary) {
this.name = name;
this.salary = salary;
}
describe() { return `${this.name} earns ₹${this.salary}`; }
}
class Manager extends Employee {
constructor(name, salary, team) {
super(name, salary);
this.team = team;
}
describe() { return super.describe() + ` and manages ${this.team.length} people`; }
}
const m = new Manager("Rahul", 72000, ["Sara", "David"]);
console.log(m.describe());
console.log(m instanceof Employee);Output
Rahul earns ₹72000 and manages 2 people true
Polymorphism
Example
Different classes can be used the same way when they share method names:
class Shape { area() { return 0; } }
class Circle extends Shape { constructor(r) { super(); this.r = r; } area() { return Math.PI * this.r ** 2; } }
class Rect extends Shape { constructor(w, h) { super(); this.w = w; this.h = h; } area() { return this.w * this.h; } }
for (const s of [new Circle(1), new Rect(2, 3)]) {
console.log(s.constructor.name, s.area().toFixed(2));
}Output
Circle 3.14 Rect 6.00