menu

JavaScript/Typescript - 16 Topics

DEEP DIVE INTO

JavaScript/Typescript

Topic:access modifiers (public, private, protected)

menu

In TypeScript, access modifiers—public, private, and protected—are used to control the visibility and accessibility of class members (properties and methods) within a class and its subclasses. They play a crucial role in enforcing encapsulation and managing the access to class members. Let's delve deeper into these access modifiers:

public:

  • Default Modifier: If no access modifier is specified, members are considered public by default.

  • Accessible Everywhere: public members are accessible from inside the class, from instances of the class, and even from external sources.

Example:

javascriptclass Car {
  public make: string;
  public model: string;

  constructor(make: string, model: string) {
    this.make = make;
    this.model = model;
  }

  public getInfo(): string {
    return `Make: ${this.make}, Model: ${this.model}`;
  }
}

private:

  • Restricted Access: private members are only accessible within the class they are declared in.

  • Inaccessible from Outside: They cannot be accessed from outside the class or from instances of the class.

Example:

javascriptclass BankAccount {
  private balance: number;

  constructor(initialBalance: number) {
    this.balance = initialBalance;
  }

  private deduct(amount: number) {
    this.balance -= amount;
  }
}

protected:

  • Accessible in Subclasses: protected members are accessible within the class they are declared in and its subclasses (classes that inherit from it).

  • Not Accessible from Instances: They cannot be accessed from instances of the class directly.

Example:

javascriptclass Animal {
  protected sound: string;

  constructor(sound: string) {
    this.sound = sound;
  }
}

class Dog extends Animal {
  makeSound() {
    console.log(`The dog makes a ${this.sound} sound.`);
  }
}

Key Points:

  • Access modifiers enforce encapsulation and control the visibility of class members.

  • public members allow broad access, private restricts access to the defining class only, and protected allows access within inheriting classes.

  • TypeScript's compiler enforces these access controls at compile-time, contributing to code reliability and maintainability.

Use Cases:

  • public is commonly used for members meant to be accessible from outside the class.

  • private is useful for sensitive data or implementation details that should not be exposed outside the class.

  • protected is employed when a class's property or method needs to be accessed by subclasses.

Understanding and using access modifiers in TypeScript is fundamental for writing maintainable and secure object-oriented code, ensuring proper encapsulation and controlling the accessibility of class members based on specific design considerations.

1280 x 720 px