Inheritance allows a class to inherit properties and methods from another class. The derived class (child class) inherits the behavior of the base class (parent class) and can also add its own behavior or override inherited methods.
Example 1: Basic Inheritance
class Animal {
move(distanceInMeters: number = 0) {
console.log(`Animal moved ${distanceInMeters}m.`);
}
}
class Dog extends Animal {
bark() {
console.log("Woof! Woof!");
}
}
const dog = new Dog();
dog.bark(); // Dog's own method
dog.move(10); // Inherited method from Animal
dog.bark(); // Dog's own method- The
Dogclass extends theAnimalclass, inheriting itsmovemethod. - The
Dogclass also adds its ownbarkmethod.
Example 2: Constructor Inheritance and Method Overriding
class Animal {
name: string;
constructor(theName: string) {
this.name = theName;
}
move(distanceInMeters: number = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
class Snake extends Animal {
constructor(name: string) {
super(name); // Call the parent class constructor
}
move(distanceInMeters = 5) {
console.log("Slithering...");
super.move(distanceInMeters); // Call the base class move method
}
}
class Horse extends Animal {
constructor(name: string) {
super(name); // Call the parent class constructor
}
move(distanceInMeters = 45) {
console.log("Galloping...");
super.move(distanceInMeters); // Call the base class move method
}
}
let sam = new Snake("Sammy the Python");
let tom: Animal = new Horse("Tommy the Palomino");
sam.move(); // Snake's move method (overridden)
tom.move(34); // Horse's move method (overridden)- Constructor Inheritance: The
SnakeandHorseclasses call the parent class constructor (super(name)) to initialize thenameproperty. - Method Overriding: Both
SnakeandHorseoverride themovemethod fromAnimal.- The
Snakeclass customizes the move method with “Slithering…” and then callssuper.move()to retain the base behavior. - The
Horseclass customizes the move method with “Galloping…” and similarly callssuper.move()to retain the base behavior.
- The
Key Points:
- Inheritance allows a child class to inherit properties and methods from a parent class using the
extendskeyword. - A child class can override methods from the parent class to provide its own implementation.
- The
superkeyword is used to call the parent class’s methods or constructor.