JS Learning

Inheritance and Polymorphism

Object-Oriented ProgrammingSection 2 of 2intermediate

Topic Overview

Take your time to understand each concept. Practice with the examples below!

Inheritance is like a family tree for classes - child classes inherit traits from their parents and can add their own unique features. It's a powerful way to build on existing code!

What is Inheritance? Inheritance allows you to create new classes based on existing ones. The child class gets all the properties and methods of the parent, plus it can add new ones or modify existing ones.

Key Concepts:

  • Parent/Base class:The class being inherited from
  • Child/Derived class:The class that inherits
  • extends keyword:How you set up inheritance
  • super keyword:Access the parent class

Why Use Inheritance?

  • Code reuse:Don't repeat yourself - inherit common functionality
  • Logical hierarchy:Model real-world relationships
  • Polymorphism:Treat different objects the same way
  • Extensibility:Easy to add new types without changing existing code

The "Is-A" Relationship:

  • A Dog "is an" Animal ✓
  • A Car "is a" Vehicle ✓
  • A Manager "is an" Employee ✓

If it makes sense to say "X is a Y", inheritance might be appropriate!

Method Overriding:

Child classes can provide their own version of parent methods:

  • Same method name and parameters
  • Can call parent method with super
  • Add extra functionality or completely replace

Abstract Classes:

  • Templates that can't be instantiated directly
  • Define methods that children must implement
  • Provide some shared implementation
  • Perfect for defining common interfaces

Real-World Example:

Think of a video game with different character types:

  • Base class:Character (health, name, move())
  • Warrior:extends Character, adds armor, sword attack
  • Mage:extends Character, adds mana, cast spells
  • Archer:extends Character, adds arrows, ranged attack

Example

// Base class
abstract class Animal {
protected name: string;
protected species: string;
constructor(name: string, species: string) {
this.name = name;
this.species = species;
}
// Abstract method - must be implemented by subclasses
abstract makeSound(): string;
// Concrete method
public introduce(): string {
return `I'm ${this.name}, a ${this.species}`;
}
protected getName(): string {
return this.name;
}
}
// Inherited classes
class Dog extends Animal {
private breed: string;
constructor(name: string, breed: string) {
super(name, "Dog");
this.breed = breed;
}
public makeSound(): string {
return "Woof! Woof!";
}
public fetch(): string {
return `${this.getName()} is fetching the ball!`;
}
public getBreed(): string {
return this.breed;
}
}
class Cat extends Animal {
private isIndoor: boolean;
constructor(name: string, isIndoor: boolean = true) {
super(name, "Cat");
this.isIndoor = isIndoor;
}
public makeSound(): string {
return "Meow!";
}
public climb(): string {
return `${this.getName()} is climbing!`;
}
}
// Polymorphism example
const animals: Animal[] = [
new Dog("Buddy", "Golden Retriever"),
new Cat("Whiskers", true),
new Dog("Max", "Bulldog")
];
animals.forEach(animal => {
console.log(animal.introduce());
console.log(animal.makeSound());
});