1.An encapsulated bank account
IntermediateWrite a class BankAccount with a private balance, deposit(double), boolean withdraw(double) (refusing amounts above the balance) and getBalance(). Deposit 1000, withdraw 300, try to withdraw 5000, and print the results.
Show hint
Keep the field private, so it can only change through the methods that enforce the rules.
Show solution
class BankAccount {
private double balance;
void deposit(double amount) {
if (amount > 0) balance += amount;
}
boolean withdraw(double amount) {
if (amount <= 0 || amount > balance) return false;
balance -= amount;
return true;
}
double getBalance() {
return balance;
}
}
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
acc.deposit(1000);
System.out.println(acc.withdraw(300) + " " + acc.withdraw(5000));
System.out.println(acc.getBalance());
}
}true false
700.0