Access modifiers help you enforce encapsulation — a key concept in object-oriented programming.
They allow you to control where and how class properties and methods are used.
✅ public (Default)
🔓 Accessible everywhere — inside the class, outside the class, and in subclasses.
class Car {
public brand: string;
constructor(brand: string) {
this.brand = brand;
}
showBrand() {
console.log(this.brand);
}
}
const car = new Car("Toyota");
console.log(car.brand); // ✅ OK✅ public is default if you don't explicitly write anything.
🔒 private
🔐 Accessible only inside the class where it is defined.
❌ Cannot be accessed from outside or from subclasses.
class BankAccount {
private balance: number;
constructor(balance: number) {
this.balance = balance;
}
getBalance() {
return this.balance;
}
}
const acc = new BankAccount(1000);
// console.log(acc.balance); // ❌ Error: Property 'balance' is private
console.log(acc.getBalance()); // ✅ OK✅ Use private for sensitive or internal logic, like passwords or internal calculations.
🟡 protected
🟡 Accessible inside the class AND in derived (child) classes,
❌ but NOT accessible from outside the class.
class Employee {
protected id: number;
constructor(id: number) {
this.id = id;
}
}
class Manager extends Employee {
getId() {
return this.id; // ✅ OK
}
}
const emp = new Manager(101);
// console.log(emp.id); // ❌ Error: Property 'id' is protected✅ Use protected for things that subclasses need but the outside world doesn't.
🧪 Quick Comparison Table
Modifier | Inside Class | Subclass | Outside Class |
|---|---|---|---|
| ✅ | ✅ | ✅ |
| ✅ | ❌ | ❌ |
| ✅ | ✅ | ❌ |
🧠 Tip: Use with Constructor Shortcut
class Student {
constructor(
public name: string,
private id: number,
protected batch: string
) {}
getId() {
return this.id;
}
}✅ This short syntax automatically creates and initializes properties with access modifiers.
✅ Summary
Use
publicfor open API-like properties/methodsUse
privateto protect internal dataUse
protectedto share data only with child classes