-
Book Overview & Buying
-
Table Of Contents
Clean Code with TypeScript
By :
Inheritance and composition are fundamental concepts in object-oriented programming that define relationships between classes. Inheritance establishes a "parent-child" hierarchy, where the child class inherits properties and behaviors from the parent. Composition, on the other hand, describes how an object is built from other objects.Inheritance is useful when there is a clear “is-a” relationship between two classes. For example, a Dog is a kind of Animal. They share common characteristics and behaviors (like eating and moving) that can be defined in the Animal class and inherited by Dog. This promotes code reuse and reduces redundancy.Let’s check the code below for more details:
class Animal {
breathe() {
console.log('Breathing');
}
}
class Dog extends Animal {
bark() {
console.log('Barking');
}
}
let dog = new Dog();
dog.breathe(); // Outputs: 'Breathing'...