Inheritance and Polymorphism
Protected Members
Protected members are available inside a class and its subclasses, but not to outside callers.
Protected Members
protected.ts
class Account {
protected cents: number;
constructor(cents: number) {
this.cents = cents;
}
}
class SavingsAccount extends Account {
addInterest(rate: number): void {
const interest: number = this.cents * rate;
this.cents = this.cents + interest;
}
balance(): number {
return this.cents;
}
}
const rate: number = ;
const account: SavingsAccount = new SavingsAccount(1000);
account.addInterest(rate);
console.log(`balance=${account.balance()}`);
class Account {
protected cents: number;
constructor(cents: number) {
this.cents = cents;
}
}
class SavingsAccount extends Account {
addInterest(rate: number): void {
const interest: number = this.cents * rate;
this.cents = this.cents + interest;
}
balance(): number {
return this.cents;
}
}
const rate: number = ;
const account: SavingsAccount = new SavingsAccount(1000);
account.addInterest(rate);
console.log(`balance=${account.balance()}`);
class Account {
protected cents: number;
constructor(cents: number) {
this.cents = cents;
}
}
class SavingsAccount extends Account {
addInterest(rate: number): void {
const interest: number = this.cents * rate;
this.cents = this.cents + interest;
}
balance(): number {
return this.cents;
}
}
const rate: number = ;
const account: SavingsAccount = new SavingsAccount(1000);
account.addInterest(rate);
console.log(`balance=${account.balance()}`);
protected
`protected` marks a member that subclasses can use while ordinary callers cannot.