Problem overview
The task is to build a BankAccount class that keeps its balance in a private double field. Outside code can't read or write that field. It has to go through four members:
BankAccount(double initialBalance)creates an account with a starting balance.deposit(double amount)adds money, and does nothing whenamountis zero or negative.withdraw(double amount)removes money and returnstrue. It returnsfalseand changes nothing whenamountis zero or negative, or larger than the balance. Withdrawing exactly the whole balance is allowed.getBalance()returns the current balance.
The driver starts at 100, deposits 50, withdraws 30 and then tries to withdraw 200, which is refused. The balance is 120. It then tries deposit(-20), deposit(0) and withdraw(-5), all ignored, and prints 120 again. Withdrawing 120 succeeds and leaves 0, and withdrawing 1 more is refused:
Balance: 120
Balance: 120
Withdrew all
Balance: 0
Rejected
Approach: let the object guard its own data
This is encapsulation. If balance were a public field, any code could write account.balance = -1000 and break the account. Because the field is private, only the methods of BankAccount can touch it, and those methods are the one place where the rules are checked. Every rule becomes a guard: a check at the top of a method that leaves early when the request is invalid, so the code that changes the balance runs only for valid amounts.
Two guards are needed. deposit rejects amount <= 0. withdraw rejects amount <= 0 and also amount > balance. The comparison with the balance is strict, so an amount equal to the balance gets through and empties the account.
The two methods answer differently. deposit returns void because ignoring a bad amount is silent. withdraw returns a boolean so the caller can tell whether the money left, which is how the driver prints Withdrew all and Rejected.
Reading the driver against the guards: withdraw(200) fails the amount > balance test because 200 is more than 150 minus 30. deposit(-20), deposit(0) and withdraw(-5) all fail the amount <= 0 test. withdraw(120) passes both tests, because 120 is not more than 120, so the balance becomes 0. The final withdraw(1) then fails the comparison with the balance, and the driver prints Rejected.
Step by step
- Declare the class
BankAccount, above the driver. Everything about the account lives inside it. - Add the private field
double balance. This is the hidden state. - Write the constructor. It is public, has the class's name and no return type, and takes
initialBalance. - Store the starting value: assign
initialBalancetobalance. - Start
deposit: public,void, with adouble amountparameter. - Guard it. A one-line
if (amount <= 0) return;leaves at once for a bad amount. - Add the amount to
balancebelow the guard. - Start
withdraw: public, returningboolean, with adouble amountparameter. - Guard it with both refusals in one condition, returning
false. - Subtract the amount from
balance. - Return
true: reaching this line means the withdrawal happened. - Add the getter
getBalance, public, returningdouble, with no parameters. - Return
balancefrom it. This is the only way outside code can read the value.
The solution in Java
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
balance = initialBalance;
}
public void deposit(double amount) {
if (amount <= 0) return;
balance += amount;
}
public boolean withdraw(double amount) {
if (amount <= 0 || amount > balance) return false;
balance -= amount;
return true;
}
public double getBalance() {
return balance;
}
}
class Solution {
public void mainFunction() {
BankAccount account = new BankAccount(100);
account.deposit(50);
account.withdraw(30);
account.withdraw(200);
System.out.println("Balance: " + (int)account.getBalance());
account.deposit(-20);
account.deposit(0);
account.withdraw(-5);
System.out.println("Balance: " + (int)account.getBalance());
if (account.withdraw(120)) {
System.out.println("Withdrew all");
}
System.out.println("Balance: " + (int)account.getBalance());
if (!account.withdraw(1)) {
System.out.println("Rejected");
}
}
}
Java details worth knowing:
privateis per class, not per object. Code outsideBankAccount, such asSolution, can't writeaccount.balance; the compiler rejects it. Only the class's own methods can.- A guard with
return;in avoidmethod. It exits the method without a value. Inwithdrawthe guard returnsfalseinstead, because the method must return abooleanon every path. ||short-circuits. Inamount <= 0 || amount > balance, the second comparison is evaluated only when the first is false. Either one being true is enough to refuse.- The
(int)cast in the driver only affects printing.(int)account.getBalance()drops the fractional part, which is why the output readsBalance: 120and notBalance: 120.0. It truncates rather than rounds: an account holding 120.75 prints120through the cast, whilegetBalance()returns120.75. - The constructor and field share no name here. The parameter is
initialBalance, sobalance = initialBalance;needs nothis..
Edge cases and common mistakes
- Using
amount >= balance. That would refuse the withdrawal of exactly 120 from a balance of 120, and the driver would never printWithdrew all. - Forgetting the
amount <= 0check inwithdraw. A call likewithdraw(-5)would pass theamount > balancetest and then subtract a negative number, which adds money. - Changing the balance before checking. The guards come first, so a refused request never touches the state.
- Returning nothing from
withdraw. The driver uses the result inif (account.withdraw(120)), so it has to be aboolean. - Floating-point rounding.
doublecan't store most decimal fractions exactly. Depositing 0.1 three times into an empty account makesgetBalance()return0.30000000000000004. The lesson's amounts are whole numbers, so the tests don't run into this. NaN. Every comparison withNaNis false, soamount <= 0doesn't catch it.deposit(Double.NaN)on an account holding 50 leaves the balance asNaN. The lesson's tests never pass it.
Testing
- A new account with 10:
withdraw(10.0001)returnsfalse, thenwithdraw(10)returnstrueandgetBalance()returns0.0. - An account with 120.75:
(int)account.getBalance()gives120, andgetBalance()itself gives120.75.
