In object-oriented programming, access modifiers play a crucial role in defining the visibility and accessibility of class members (attributes and methods). Understanding public, private, and protected modifiers is essential for maintaining encapsulation and ensuring that the code is organized and secure. Below is an overview of these modifiers, their practical applications, best practices, and common mistakes.
The public modifier allows class members to be accessible from any other code in the same program. This means that any object of the class can access its public attributes and methods.
class User {
public name;
constructor(name) {
this.name = name;
}
public greet() {
return `Hello, ${this.name}!`;
}
}
const user = new User('Alice');
console.log(user.greet()); // Output: Hello, Alice!
The private modifier restricts access to class members, allowing them to be accessed only within the class itself. This encapsulation helps protect the internal state of the object.
class BankAccount {
private balance;
constructor(initialBalance) {
this.balance = initialBalance;
}
public deposit(amount) {
this.balance += amount;
}
public getBalance() {
return this.balance;
}
}
const account = new BankAccount(100);
account.deposit(50);
console.log(account.getBalance()); // Output: 150
// console.log(account.balance); // Error: balance is private
The protected modifier allows class members to be accessed within the class itself and by subclasses. This is particularly useful in inheritance scenarios where derived classes need to access or modify the base class members.
class Animal {
protected species;
constructor(species) {
this.species = species;
}
}
class Dog extends Animal {
public bark() {
return `Woof! I am a ${this.species}.`;
}
}
const dog = new Dog('Dog');
console.log(dog.bark()); // Output: Woof! I am a Dog.
// console.log(dog.species); // Error: species is protected