CHALLENGE 2: Access Modifiers ============================== SOLUTION: class BankAccount { private balance: number = 0; public deposit(amount: number): void { if (amount > 0) { this.balance += amount; console.log(`Deposited $${amount}. New balance: $${this.balance}`); } else { console.log("Deposit amount must be positive"); } } public withdraw(amount: number): void { if (amount > 0 && amount <= this.balance) { this.balance -= amount; console.log(`Withdrew $${amount}. New balance: $${this.balance}`); } else { console.log("Insufficient funds or invalid amount"); } } public getBalance(): number { return this.balance; } } // Using the bank account const account = new BankAccount(); account.deposit(100); // Deposited $100. New balance: $100 account.deposit(50); // Deposited $50. New balance: $150 account.withdraw(30); // Withdrew $30. New balance: $120 account.withdraw(200); // Insufficient funds or invalid amount console.log(account.getBalance()); // Output: 120 // This would cause an error (balance is private): // account.balance = 999999; // ❌ Error! Property 'balance' is private EXPLANATION: - "private balance: number = 0" — hidden from outside; only accessible inside the class - "public deposit(...)" — anyone can call this - "public getBalance()" — anyone can call this - Business logic is enforced: withdraw() checks for sufficient funds - Users can't cheat by directly setting balance WHY PRIVATE IS IMPORTANT: Without private, this would be possible (bad!): const account = new BankAccount(); account.balance = 1000000; // Cheating! No business logic applied With private, this is impossible: account.balance = 1000000; // ❌ Error! balance is private EXTENSION: Add a withdraw(amount) return value If you want to know if withdrawal succeeded: class BankAccount { private balance: number = 0; public withdraw(amount: number): boolean { if (amount > 0 && amount <= this.balance) { this.balance -= amount; return true; } return false; } } const success = account.withdraw(30); if (success) { console.log("Withdrawal successful"); } else { console.log("Withdrawal failed"); } KEY INSIGHT: Private properties protect data integrity. They force users to go through methods, which can validate and enforce business rules.