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
Dog
class extends theAnimal
class, inheriting itsmove
method. - The
Dog
class also adds its ownbark
method.
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
Snake
andHorse
classes call the parent class constructor (super(name)
) to initialize thename
property. - Method Overriding: Both
Snake
andHorse
override themove
method fromAnimal
.- The
Snake
class customizes the move method with “Slithering…” and then callssuper.move()
to retain the base behavior. - The
Horse
class 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
extends
keyword. - A child class can override methods from the parent class to provide its own implementation.
- The
super
keyword is used to call the parent class’s methods or constructor.