Sub topic 6
Protecting State with Constructors and Methods
An object can hold information that changes over time. This information is its state. For example, a bank account object might store a balance.
A field is a variable stored in an object. A method is a named operation that an object can perform. To keep an account reliable, its methods must not leave its balance in an invalid state.
An invariant is a rule that must remain true throughout an object’s normal use. In this chapter, our account has one main invariant:
- Its balance is never negative.
A constructor establishes that rule when the object is created. Methods preserve it as the object changes.
We will use a simple account to see how this works. The example assumes one thread of execution uses an account at a time. We will discuss why that matters near the end.
Start with a valid object
A class is a blueprint for creating objects. A constructor is a special part of a class that runs when code creates an object with new.
A constructor can require starting values and check them before the object is ready for use. For our account, it must reject a negative opening balance.
A parameter is a variable that receives a value passed to a constructor or method. The actual value passed in is an argument. For example, in new BankAccount(5000), the argument 5000 supplies the openingBalance parameter.
The constructor follows this pattern:
- Receive the proposed opening balance.
- Check that it follows the rule.
- Store it only if it is valid.
If the check fails, the constructor throws an exception instead. An exception is a signal that an operation could not complete normally. When this constructor throws an exception, the new expression does not return an account to the caller.
Build an account that controls changes
Our example stores money as a number of cents. This avoids using fractions in the example: 5000 means 50 dollars and 0 cents.
The balance uses long, a Java type for whole numbers. Its values have a limited range, so the code must also prevent a deposit from exceeding the largest value a long can hold.
Save this code in a file named BankAccount.java:
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;
}
}The word private means ordinary code outside BankAccount cannot directly read or write balance. The word public makes the constructor and the three methods available to callers. A caller is code that creates the account or uses one of its methods.
The field and the operations have different jobs:
balancestores the account’s state.BankAccountchecks and stores the starting state.getBalancereturns the current balance.depositincreases the balance after checking the request.withdrawdecreases the balance after checking the request.
Each operation works in cents. Both deposit(0) and withdraw(0) are allowed and leave the balance unchanged.
Read the constructor
The constructor has the same name as the class and no return type. Its first check rejects an opening balance below zero:
public class ConstructorExample {
public static void main(String[] args) {
BankAccount account = new BankAccount(5000);
System.out.println(account.getBalance());
}
}With BankAccount.java in the same folder, this example creates an account with a balance of 5000 cents. The constructor checks 5000, finds it valid, and assigns it to balance.
If the caller instead passes -1, the condition openingBalance < 0 is true. The constructor throws an IllegalArgumentException. This exception type signals that a supplied argument is not acceptable.
The assignment comes after the check. That order makes the intended rule clear: validate first, then store the value.
Read the methods
getBalance returns a long. Its return type says what kind of value the method gives back. A long is a primitive value, so the caller receives the number, not a way to write the account’s field.
The return type void on deposit and withdraw means those methods do not return a value. They either complete the requested change or throw an exception.
The symbol || means “or.” In each check, either invalid condition is enough to reject the request.
For a deposit, the method rejects:
- A negative amount.
- An amount too large to add safely.
For a withdrawal, the method rejects:
- A negative amount.
- An amount greater than the current balance.
Allowing a negative withdrawal would be a mistake: subtracting a negative number would increase the balance. Checking the sign makes the method’s behavior match its name.
Run the example
Save the following code in a second file named Main.java, in the same folder as BankAccount.java:
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount(5000);
System.out.println("Opening: " + account.getBalance());
account.deposit(1500);
System.out.println("After deposit: " + account.getBalance());
account.withdraw(2000);
System.out.println("After withdrawal: " + account.getBalance());
try {
account.withdraw(5000);
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
System.out.println("After rejection: " + account.getBalance());
}
}The main method is where this program starts. The try block contains an operation that may throw an exception. The catch block handles the named exception so the program can continue. Here, e.getMessage() reads the explanation supplied when the exception was created.
With a Java development kit installed, run these commands in that folder:
javac BankAccount.java Main.java
java Mainjavac compiles the source files, turning them into a form Java can run. java then starts the program. The output is:
Opening: 5000
After deposit: 6500
After withdrawal: 4500
Rejected: Invalid withdrawal
After rejection: 4500The last two lines matter. The attempted withdrawal of 5000 cents is larger than the balance of 4500 cents. The method rejects it before changing the field. The account is still valid, and its balance is unchanged.
Check before changing state
A method that changes state should check every condition needed for its operation before it makes the change. The account’s methods follow that order:
- Inspect the argument and current balance.
- Reject an invalid request.
- Update the balance only after all checks pass.
Here are some calls and their results. Each row starts with the balance shown in that row.
| Starting balance | Call | Result |
|---|---|---|
| `5000` | `deposit(1500)` | Balance becomes `6500` |
| `5000` | `withdraw(5000)` | Balance becomes `0` |
| `5000` | `withdraw(5001)` | Exception; balance stays `5000` |
| `5000` | `deposit(-1)` | Exception; balance stays `5000` |
| `5000` | `withdraw(0)` | Balance stays `5000` |
Notice that a balance of zero is valid. The invariant says the balance cannot be negative, not that it must be positive.
Keeping state unchanged after a rejected request also makes the class easier to use. The caller does not have to guess whether part of the operation happened before the error.
Prevent overflow
A long can hold large whole numbers, but it cannot hold every possible whole number. Long.MAX_VALUE is the largest value it can hold.
Overflow happens when an arithmetic result is outside the range of its type. Java does not automatically throw an exception when long addition overflows. The result wraps around and can become negative.
This means checking only that a deposit is nonnegative is not enough. A large deposit could make a valid, positive balance wrap into a negative value.
The deposit method checks this before adding:
Long.MAX_VALUE - balanceis the most that can safely be added.- If
amountis greater than that limit, the method rejects it. - Otherwise,
balance += amountis safe.
For example, if the balance is Long.MAX_VALUE - 2, depositing 2 is valid. Depositing 3 is not. The method must compare before adding; adding first and checking the result would already perform the overflowing calculation.
The withdrawal check has a similar purpose. It ensures the amount is between zero and the balance, so the subtraction cannot make the balance negative.
Why not let callers set the balance?
If outside code could assign any value directly to balance, it could set the field to -1. The constructor’s check would no longer protect the account after creation.
Making the field private creates a boundary. Callers use operations that check the rules rather than writing the field themselves. This is part of encapsulation: keeping state and the behavior that protects it together inside the class.
A method named setBalance would not automatically be safe just because it is a method. It would also need to reject invalid values. It could then allow callers to replace the balance for any reason, which may not match the account’s intended behavior.
deposit and withdraw express more specific changes. Each has a clear rule: deposits cannot be negative or overflow, and withdrawals cannot be negative or exceed the balance. Choose operations that reflect the changes the class intends to allow.
Constructors and methods share the responsibility
The constructor and methods protect the same state at different times:
- The constructor prevents an invalid starting balance.
- The methods prevent later changes from breaking the rule.
- The read method lets callers inspect the balance without changing it.
Protecting only the constructor would not be enough if later methods could write a negative balance. Protecting only the methods would not be enough if the constructor accepted a negative opening balance.
If a class has more than one constructor, each one must establish a valid starting state. Java also provides a no-argument constructor automatically only when a class declares no constructors of its own. Our class declares one, so callers must supply an opening balance.
Practice
Exercise
An account has a balance of 300 cents. What happens when the caller requests withdraw(300) and then withdraw(1)?
Show answer
The first call succeeds and leaves a balance of 0. The second throws an IllegalArgumentException and leaves the balance at 0.
Exercise
Why must deposit check for overflow as well as a negative amount?
Show answer
A nonnegative amount can still be too large to add to the current balance. Without the overflow check, the result can wrap around and become negative.
Exercise
A new method changes balance and only then checks whether the result is negative. What should change?
Show answer
Check whether the requested change is valid before assigning to balance. If the request is invalid, throw an exception without changing the field.