1. Welcome and Icebreaker:
- If you could make any part of your life private, protected, or public, what would you choose and why?
2. Outline the Session:
- We’ll learn about access modifiers in TypeScript:
public, private, and protected.
- Learning Outcomes: Understand how to control access to class members and why encapsulation is important.
- Let’s see how to protect our data!
3. Concept Explanation:
- Access Modifiers control the visibility of class properties and methods.
public: Accessible from anywhere (default).
private: Accessible only within the class.
protected: Accessible within the class and its subclasses.
- Encapsulation helps prevent unintended access or modification of data.
4. Live Coding Demonstration:
class User {
public username: string;
private password: string;
protected email: string;
constructor(username: string, password: string, email: string) {
this.username = username;
this.password = password;
this.email = email;
}
public greet() {
console.log(`Hello, ${this.username}!`);
}
private resetPassword() {
console.log("Password reset!");
}
protected sendEmail() {
console.log(`Email sent to ${this.email}`);
}
}
const user = new User("alice", "secret", "alice@example.com");
user.greet(); // OK
// user.password; // Error: private
// user.resetPassword(); // Error: private
// user.sendEmail(); // Error: protected
class Admin extends User {
promote() {
// this.password; // Error: private
this.sendEmail(); // OK: protected
}
}
5. Tasks:
- Short Exercise:
- Create a class
Account with properties: owner (public), balance (private), and accountNumber (protected).
- Add a method to deposit money (public) and a method to get the balance (public).
- Try to access
balance and accountNumber from outside the class and from a subclass.