第22章 访问修饰符
案例题目:银行账户的访问控制守卫
设计一个银行账户类,通过public、private、protected三种修饰符控制成员访问,演示封装与继承的基本规则。
设计思路
基类BankAccount包含:public账户名称、private余额、protected交易记录。子类SavingsAccount可访问protected交易记录,但无法直接访问private余额,必须通过public方法操作。
核心代码
class BankAccount {
public owner: string;
private balance: number;
protected transactions: string[] = [];
constructor(owner: string, initialBalance: number) {
this.owner = owner;
this.balance = initialBalance;
this.transactions.push(`初始存款: ${initialBalance}`);
}
public deposit(amount: number): void {
this.balance += amount;
this.transactions.push(`存款: +${amount}`);
}
public getBalance(): number {
return this.balance;
}
protected addInterest(rate: number): void {
this.balance *= (1 + rate);
this.transactions.push(`利息: +${Math.round(this.balance * rate)}`);
}
}
class SavingsAccount extends BankAccount {
constructor(owner: string, initialBalance: number) {
super(owner, initialBalance);
}
public applyMonthlyInterest(): void {
this.addInterest(0.003); // 可访问protected方法
}
public showTransactions(): void {
console.log(`${this.owner}的交易记录:`);
this.transactions.forEach(t => console.log(` ${t}`)); // protected可访问
}
}
运行结果验证
运行以下测试代码:
const acc = new SavingsAccount("张三", 1000);
acc.deposit(500);
acc.applyMonthlyInterest();
acc.showTransactions();
console.log(`最终余额: ${acc.getBalance()}`);
输出:张三的交易记录,初始存款1000、存款+500、利息+4,最终余额1504。
测试建议
尝试直接访问acc.balance会报编译错误(私有属性),访问acc.transactions同样被拒绝(受保护的)。
要点:private仅在类内部可用;protected允许子类访问;public对外完全开放。
注意:TypeScript的访问修饰符是编译期约束,运行时JavaScript仍可访问,切勿用于安全敏感场景。
成功实践:将数据设为private,通过public方法提供受控访问;将需继承复用的逻辑设为protected,减少重复代码。