Encapsulation in TypeScript: Private Attributes and Methods

Lesson Overview

Hello! In this lesson, we're revisiting Encapsulation, Private Attributes, and Private Methods in Object-Oriented Programming (OOP). Imagine encapsulation as an invisible fence safeguarding a garden from outside interference, keeping data and methods safe within. Within this garden, certain plants (Private Attributes and Methods) are only for the gardener's eyes. These are crucial for making your classes more robust and secure!

Encapsulation Explained

Encapsulation in OOP wraps up data and methods into a class. This organizational approach tidies the code and reinforces security. If you were to code a multiplayer game, for example, you could create a Player class, encapsulating data (health, armor, stamina) and methods (receiveDamage, shieldHit, restoreHealth).

class Player {
    private health: number;
    private armor: number;
    private stamina: number;

    constructor(health: number, armor: number, stamina: number) {
        this.health = health;
        this.armor = armor;
        this.stamina = stamina;
    }

    receiveDamage(damage: number): void {
        this.health -= damage;
    }

    shieldHit(armor: number): void {
        this.armor -= armor;
    }

    restoreHealth(healthIncrease: number): void {
        this.health += healthIncrease;
    }
}

const player = new Player(100, 50, 77);

Now, player is an instance of the Player class on which you can call methods. You may notice the private keyword in the Player class definition; we will discuss the private keyword in the next section.

Remark the Privacy

In TypeScript, private attributes and methods are designated using the private keyword. Note that the constructor itself cannot be private.

class PrivateExample {
    private privateAttribute: string;

    constructor() {
        this.publicAttribute = "Public";
        this.privateAttribute = "Private";
    }

    publicAttribute: string;

    getPrivateAttribute(): string {
        return this.privateAttribute;
    }
}

const example = new PrivateExample();
console.log(example.publicAttribute);  // Works: logs "Public"
console.log(example.getPrivateAttribute());  // Works: logs "Private"
// console.log(example.privateAttribute);  // Error: can't access private attribute from outside

Private attributes and methods are inaccessible directly from an instance. This arrangement helps maintain integrity.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal