Inheritance
In this page:
Basic Inheritance
A derived class uses extends to inherit from a base class, and the derived class automatically gains access to the base class's public and protected members without having to redeclare them.
Example: Basic Inheritance
class Animal {
eat() { console.log("Eating"); }
}
class Dog extends Animal {
bark() { console.log("Barking"); }
}
const dog = new Dog();
dog.eat();
dog.bark();
Inherited Properties
A derived class can use properties declared by its base class according to their visibility — public and protected members are inherited and usable, while private members remain locked to the base class alone.
Example: Inherited Properties
class Animal {
public name: string = "Animal";
protected sound: string = "...";
}
class Dog extends Animal {
describe() {
console.log(this.name, this.sound);
}
}
new Dog().describe();
Calling the Base Constructor
When a derived class defines its own constructor, it must call the base class constructor with super(...) before it can access this, ensuring the inherited part of the object is fully initialized first.
Example: Calling the Base Constructor
class Animal {
constructor(public name: string) {}
}
class Dog extends Animal {
constructor(name: string, public breed: string) {
super(name);
}
}
const d = new Dog("Rex", "Labrador");
console.log(d.name, d.breed);
Method Overriding
A derived class can provide its own implementation of an inherited method; the override keyword documents this intent explicitly and lets the compiler catch mistakes like misspelling the method name.
Example: Method Overriding
class Animal {
speak() { console.log("..."); }
}
class Dog extends Animal {
override speak() { console.log("Woof"); }
}
new Dog().speak();
Benefits of Inheritance
Inheritance reduces repeated code and models real relationships between related types, such as a Manager class extending Employee, but it should be reached for only when a genuine is-a relationship exists between the classes.
Example: Benefits of Inheritance
class Employee {
constructor(public name: string) {}
}
class Manager extends Employee {
manageTeam() { console.log(`${this.name} manages the team`); }
}
new Manager("Riya").manageTeam();
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: