Enhancing Skills

Inheritance in JavaScript

Inheritance is a fundamental concept in object-oriented programming that allows one class (subclass) to inherit properties and methods from another class (superclass). This promotes code reuse and establishes a natural hierarchy between classes.

Command Description

  1. Extending Classes with extends:
  • The extends keyword is used to create a subclass that inherits from a superclass. The subclass gains access to the properties and methods of the superclass.
  1. Superclass and Subclass Relationships:
  • A superclass is a class that is extended by another class. The subclass can utilize and build upon the functionality provided by the superclass.
  1. Method Overriding:
  • Subclasses can override methods defined in their superclass. This allows the subclass to provide a specific implementation of a method that is already defined in the superclass.

Sample Code

// Superclass
class GameCharacter {
    constructor(name, health) {
        this.name = name;
        this.health = health;
    }

    attack(target) {
        console.log(`${this.name} attacks ${target.name}`);
    }

    // Method to display character info
    displayInfo() {
        console.log(`Character: ${this.name}, Health: ${this.health}`);
    }
}

// Subclass
class Warrior extends GameCharacter {
    constructor(name, health, weapon) {
        super(name, health); // Call the superclass constructor
        this.weapon = weapon;
    }

    // Overriding the attack method
    attack(target) {
        console.log(`${this.name} swings their ${this.weapon} at ${target.name}!`);
    }

    // New method specific to Warrior
    useWeapon() {
        console.log(`${this.name} uses their ${this.weapon}!`);
    }
}

// Subclass
class Mage extends GameCharacter {
    constructor(name, health, spell) {
        super(name, health); // Call the superclass constructor
        this.spell = spell;
    }

    // Overriding the displayInfo method
    displayInfo() {
        console.log(`Character: ${this.name}, Health: ${this.health}, Spell: ${this.spell}`);
    }

    castSpell(target) {
        console.log(`${this.name} casts ${this.spell} on ${target.name}!`);
    }
}

// Creating instances of subclasses
const knight = new Warrior('Knight', 120, 'sword');
const wizard = new Mage('Wizard', 100, 'fireball');

knight.attack(wizard); // Calls the overridden method
wizard.attack(knight);  // Calls the inherited method
knight.useWeapon();     // Calls the specific method
wizard.castSpell(knight); // Calls the specific method

// Displaying info
knight.displayInfo(); // Calls the inherited method
wizard.displayInfo(); // Calls the overridden method

Output

Knight swings their sword at Wizard!
Wizard attacks Knight
Knight uses their sword!
Wizard casts fireball on Knight!
Character: Knight, Health: 120
Character: Wizard, Health: 100, Spell: fireball

Use Case

  • Code Reusability: Inheritance allows you to create a base class (like GameCharacter) that contains common properties and methods. Specific classes (like Warrior and Mage) can inherit these properties and methods, reducing redundancy in your code.
  • Hierarchical Structure: Inheritance establishes a clear relationship between different types of characters in your game. For example, all characters can inherit common behaviors (like attack), while still having their unique characteristics (like weapon for warriors and spell for mages).
  • Method Overriding: Subclasses can provide their own specific implementations of inherited methods, enabling customization of behaviors while maintaining the overall structure. This is particularly useful when different character types have variations of similar actions (like attacking).
  • Flexibility in Game Design: By using inheritance, you can easily extend your game’s functionality. If you want to add a new character type (e.g., Archer), you can simply create a new subclass that extends GameCharacter, defining its specific behaviors without needing to rewrite the existing character logic.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.