Access Modifiers

Control visibility of class members with public, private, and protected.

Syntaxprivate balance: number;

Access modifiers control who can see a class member:

  • public — accessible everywhere (the default).
  • private — only inside the same class.
  • protected — inside the class and its subclasses.

They help you hide internal details and expose a clean interface.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A BankAccount class marks balance as private to prevent direct manipulation, exposing only deposit and withdraw methods.
  • A base Entity class uses protected id so subclasses can read it while external code cannot.
  • A public API class exposes only the methods marked public, hiding internal helpers marked private.

More examples

public, private, protected

Applies all three access modifiers to demonstrate encapsulation — balance is private, accountNumber protected, owner public.

Example · ts
class BankAccount {
  public owner: string;
  private balance: number;
  protected accountNumber: string;

  constructor(owner: string, initial: number) {
    this.owner = owner;
    this.balance = initial;
    this.accountNumber = Math.random().toString(36).slice(2);
  }

  public deposit(amount: number): void {
    this.balance += amount;
  }

  public getBalance(): number {
    return this.balance;
  }
}

Subclass accesses protected

Shows that a subclass can access a protected member from the base class while external callers cannot.

Example · ts
class SavingsAccount extends BankAccount {
  getInfo(): string {
    // accountNumber is protected: accessible in subclass
    return `Account ${this.accountNumber} owned by ${this.owner}`;
  }
}

const sa = new SavingsAccount('Alice', 1000);
console.log(sa.getInfo());
// sa.accountNumber; // Error: protected, not accessible outside class

Private method

Declares a private helper method that is called internally but blocked from external callers.

Example · ts
class Formatter {
  private sanitize(input: string): string {
    return input.trim().toLowerCase();
  }

  public format(text: string): string {
    return this.sanitize(text); // internal use only
  }
}

const f = new Formatter();
f.format('  HELLO  '); // OK
// f.sanitize('...'); // Error: 'sanitize' is private

Discussion

  • Be the first to comment on this lesson.
Access Modifiers — TypeScript | SoundsCode