Overview
Inheritance and Polymorphism are two core pillars of OOP that allow developers to create generic interfaces and reuse code efficiently.
Core Concepts
- Inheritance: A mechanism where a new class (Derived/Child) inherits properties and methods from an existing class (Base/Parent). This represents an “is-a” relationship.
- Method Overriding: When a child class provides a specific implementation for a method already defined in its parent class.
- Polymorphism: The ability of different classes to be treated as instances of the same parent class through a uniform interface.
- Compile-time (Static): Method Overloading (same method name, different parameters).
- Runtime (Dynamic): Method Overriding (the method called is determined by the actual object type at runtime).
- Abstract Classes: Classes that cannot be instantiated and are designed to be inherited from.
Code Examples
abstract class Animal {
abstract makeSound(): void;
sleep() { console.log("Zzz..."); }
}
class Dog extends Animal {
makeSound() { console.log("Woof!"); }
}
class Cat extends Animal {
makeSound() { console.log("Meow!"); }
}
const pets: Animal[] = [new Dog(), new Cat()];
pets.forEach(pet => pet.makeSound()); // Polymorphism in action
Use Cases
- Frameworks: Defining a base
ControllerorServiceclass that all specific implementations must extend. - Payment Systems: A base
PaymentMethodclass with subclasses likeCreditCard,PayPal, andCrypto.
Gotchas
- Tight Coupling: Strong inheritance creates a rigid link between parent and child. If the parent changes, all children may break.
- Prefer Composition over Inheritance: A common design principle suggesting that building objects via composition is often more flexible than deep inheritance trees.
