Summary - Access modifiers
- TypeScript course
- Intermediate
- Lesson 10/89
- 4 min
Write a user class encapsulated with modifiers.
Summary - Access modifiers
A User class combines access modifiers: public name for everyone, private password fully hidden, protected role open to subclasses. Each field is declared with its own modifier and assigned with this in the constructor.
class User {
public name: string;
private password: string;
protected role: string;
constructor(name: string, password: string, role: string) {
this.name = name;
this.password = password;
this.role = role;
}
checkPassword(pw: string): boolean {
return this.password === pw;
}
}
class Admin extends User {
getRole(): string {
return this.role;
}
}Practice Write an encapsulated User class
Define a User class: explicitly declare public name: string and private password: string fields. Add a constructor that takes name and password parameters and assigns them with this. Write a checkPassword(pw: string): boolean method that returns this.password === pw. Create a new User("Ada", "s3cr3t"), call checkPassword("s3cr3t") and checkPassword("wrong").
Starter code
// User sınıfı tanımla (public name, private password)
// constructor ile her ikisini al, this ile ata
// checkPassword(pw: string): boolean metodu yaz
// password === pw ise true döndür
// yeni User oluştur, checkPassword çağırSample solution
class User {
public name: string;
private password: string;
constructor(name: string, password: string) {
this.name = name;
this.password = password;
}
checkPassword(pw: string): boolean {
return this.password === pw;
}
}
const u = new User("Ada", "s3cr3t");
console.log(u.checkPassword("s3cr3t"));
console.log(u.checkPassword("wrong"));Expected output
true false
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which modifier should the password field use in a User class?
- public
- protected
- static
- private Correct answer
Explanation: Sensitive information like a password should be private; accessible only inside the class. public would be open to everyone, protected would be open to subclasses; both are unsafe.
2 Complete the password check
checkPassword(pw: string): boolean {
return this.password ____ pw;
}
checkPassword(pw: string): boolean {
return this.password === pw;
}
Explanation: Password comparison uses strict equality: this.password === pw. == does type coercion (risky), = does assignment (not boolean), and !== gives the opposite result.
3 Encapsulated User parts
| Term | Meaning |
|---|---|
public name |
Public name for everyone |
private password |
Hidden password |
protected role |
Role open to subclass |
extends User |
Subclass definition |