Part 3: Inheritance and Polymorphism - Code Reuse and Flexibility
Introduction
The Problem: Code Duplication
class PhysicalProduct {
constructor(
public id: string,
public name: string,
public price: number,
public weight: number
) {}
calculatePrice(): number {
return this.price;
}
applyDiscount(percent: number): void {
this.price -= this.price * (percent / 100);
}
getShippingCost(): number {
return this.weight * 0.5;
}
}
class DigitalProduct {
constructor(
public id: string,
public name: string,
public price: number,
public fileSize: number // MB
) {}
// Duplicate code!
calculatePrice(): number {
return this.price;
}
// Duplicate code!
applyDiscount(percent: number): void {
this.price -= this.price * (percent / 100);
}
getDownloadUrl(): string {
return `https://downloads.example.com/${this.id}`;
}
}The Solution: Inheritance
Inheritance Basics
Extends Keyword
Method Overriding
Using super
Polymorphism
Abstract Classes
Real Example: Notification System
Real Example: User Roles and Permissions
Protected vs Private
Method Override Rules
Best Practices
1. Favor Composition Over Deep Inheritance
2. Use Abstract Classes for Shared Behavior
3. Keep Inheritance Hierarchies Shallow
4. Call super() First in Constructor
What's Next
PreviousPart 2: Encapsulation and Access Modifiers - Data ProtectionNextPart 4: Interfaces and Composition - Contracts and Flexibility
Last updated