Sub topic 6
Protecting State with Constructors and Methods
An object is a value created from a class, which is a plan for that value. An object’s state is the information it holds in its fields. A field is a variable that belongs to an object.
Encapsulation means keeping that state behind controlled operations. This lets a class protect an invariant: a rule that must stay true throughout an object’s life.
For example, a bank account can have this invariant: its balance must never be negative. The account needs to protect that rule when it is created and whenever its balance changes.
Start with a valid object
A constructor is code that runs when an object is created. It can check the values needed to set up the object.
For our account, the constructor accepts an opening balance. If the balance is negative, the constructor rejects it. Otherwise, it stores the value.
The account also needs methods, which are named operations on an object. A deposit method can add money, and a withdrawal method can remove it. Each method must check its input before changing the balance.
Build a bank account
Save this code in a file named BankAccount.java. The name matches the public class in the file.
public class BankAccount {
private long balance;
public BankAccount(long openingBalance) {
if (openingBalance < 0) {
throw new IllegalArgumentException("Negative opening balance");
}
balance = openingBalance;
}
public long getBalance() {
return balance;
}
public void deposit(long amount) {
if (amount < 0 || amount > Long.MAX_VALUE - balance) {
throw new IllegalArgumentException("Invalid deposit");
}
balance += amount;
}
public void withdraw(long amount) {
if (amount < 0 || amount > balance) {
throw new IllegalArgumentException("Invalid withdrawal");
}
balance -= amount;
}
public static void main(String[] args) {
BankAccount account = new BankAccount(5000);
account.deposit(1200);
account.withdraw(3000);
System.out.println("Balance: " + account.getBalance() + " cents");
try {
account.withdraw(4000);
} catch (IllegalArgumentException e) {
System.out.println("Withdrawal rejected");
}
System.out.println("Balance: " + account.getBalance() + " cents");
}
}The main method is where Java starts this example. Run these commands from the folder containing the file:
javac BankAccount.java
java BankAccountThe output is:
Balance: 3200 cents
Withdrawal rejected
Balance: 3200 centsFollow the checks
The account stores money as a number of cents. Its long type is a Java whole-number type with a limited range. For example, 5000 cents represents 50 dollars.
The private keyword means code outside BankAccount cannot write the balance field directly. The public methods provide the operations that other code can call instead. getBalance returns the current number; changing that returned number does not change the account.
Here is how the other operations protect the invariant:
- The constructor rejects a negative opening balance.
depositrejects a negative amount. It also checks that the new balance will fit in along.withdrawrejects a negative amount or an amount greater than the balance.
Zero is allowed as an opening balance, deposit, or withdrawal. A zero deposit or withdrawal leaves the balance unchanged.
Long.MAX_VALUE is the largest value a long can hold. The deposit check compares the amount with the space left before that limit. It does this before adding, so the addition cannot overflow. Overflow happens when a number goes beyond the range its type can hold and the result wraps around.
When a check fails, the code throws an IllegalArgumentException. An exception is a signal that an operation could not proceed normally. The try and catch block in main handles the failed withdrawal, so the program can print the balance afterward.
The failed withdrawal does not change the balance because the check happens before subtraction. The same is true for a failed deposit: it is rejected before addition.
Exercise
An account has a balance of 3200 cents. What happens if it receives a withdrawal request for 4000 cents?
Show answer
The method throws an IllegalArgumentException before subtracting. The balance remains 3200 cents.
Exercise
Why does deposit check the amount against Long.MAX_VALUE - balance before adding it?
Show answer
To reject an amount that would make the balance overflow the long range.