TypeScript BankAccount Class with Private and Protected Properties
TypeScript Classes and OOP : Exercise-18 with Solution
Write a TypeScript class called BankAccount with the following properties and methods:
- private accountNumber: string
- protected balance: number
The class should have a constructor that accepts an account number and initializes the balance to 0. It should also include methods:
public deposit(amount: number): void to add funds to the account.
public withdraw(amount: number): void to deduct funds from the account.
Only the class and its subclasses should have access to the balance property.
Sample Solution:
TypeScript Code:
class BankAccount {
private accountNumber: string;
protected balance: number;
constructor(accountNumber: string) {
this.accountNumber = accountNumber;
this.balance = 0;
}
public deposit(amount: number): void {
if (amount > 0) {
this.balance += amount;
console.log(`Deposited $${amount}. New balance: $${this.balance}`);
} else {
console.log("Invalid deposit amount.");
}
}
public withdraw(amount: number): void {
if (amount > 0 && amount <= this.balance) {
this.balance -= amount;
console.log(`Withdrawn $${amount}. New balance: $${this.balance}`);
} else {
console.log("Invalid withdrawal amount or insufficient balance.");
}
}
}
// Example usage:
const bankAccount = new BankAccount("12345");
bankAccount.deposit(1200);
bankAccount.withdraw(400);
bankAccount.withdraw(1000);
Explanations:
In the exercise above -
- First, we define a "BankAccount" class with a private property 'accountNumber' and a protected property 'balance'.
- The constructor accepts an 'accountNumber' and initializes the 'balance' to 0.
- Next, we implement public methods "deposit()" and "withdraw()" to add or deduct funds from the account, respectively. These methods ensure that the provided amounts are valid and do not result in a negative balance.
- The 'balance' property is accessible only within the class and its subclasses, as requested.
Output:
"Deposited $1200. New balance: $1200" "Withdrawn $400. New balance: $800" "Invalid withdrawal amount or insufficient balance."
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript Student Class with Private and Protected Properties.
Next: TypeScript Car Class with Protected Properties.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics