Sub topic 1
Encapsulation: State, Behavior, and Invariants
Keeping an object safe
A class is a plan for making objects. An object is a working instance of a class. For example, a BankAccount object can represent one account.
An object has both state and behavior:
- State is the information the object holds. An account’s balance is part of its state. Java stores such information in fields, which are variables that belong to an object.
- Behavior is what the object can do. An account might accept a deposit or report its balance. A method is a named set of instructions that provides behavior.
Encapsulation means keeping an object’s state and the behavior that manages it together. It also means giving other code controlled ways to use the object. This helps the object stay valid.
An invariant is a rule that must stay true throughout an object’s life. For our example account, the invariant is: the balance must be between 0 and 10,000 cents, including both limits. The balance can change, but it must always obey that rule.
Encapsulation and access control
Access control is how Java limits which code can use a class or its members. A member is a field or method belonging to a class.
One access control tool is private. A private field cannot be accessed directly by ordinary code outside its class. A public method, by contrast, can be called by other code. The code that calls a method is its caller.
Access control supports encapsulation, but it does not guarantee it. A private balance is not enough if a method inside the class can still set that balance to a negative number. The class’s behavior must protect the invariant too.
Worked example: an account
This account starts at zero. Its deposit method checks an amount before changing the balance. Amounts are whole numbers of cents.
Save the following as BankAccount.java:
public class BankAccount {
private int balance = 0;
public boolean deposit(int amount) {
if (amount < 0 || amount > 10000 - balance) {
return false;
}
balance += amount;
return true;
}
public int getBalance() {
return balance;
}
public static void main(String[] args) {
BankAccount account = new BankAccount();
System.out.println(account.getBalance());
System.out.println(account.deposit(700));
System.out.println(account.deposit(-50));
System.out.println(account.deposit(10000));
System.out.println(account.getBalance());
}
}To run it, you need the Java Development Kit installed. Run these commands in the folder containing the file:
javac BankAccount.java
java BankAccountThe output is:
0
true
false
false
700Follow the changes
The field balance is private, so callers do not change it directly. The getBalance method returns its current value.
The deposit method returns a boolean, a value that is either true or false. Here, true means the deposit was accepted. false means it was rejected and the balance did not change.
The symbol || means “or.” The method rejects a deposit if the amount is negative or if it is greater than the remaining space below 10,000 cents. A deposit of zero is allowed.
| Step | Result | Balance in cents |
|---|---|---|
| Create the account | It starts at zero | 0 |
| Deposit 700 | Accepted: returns `true` | 700 |
| Deposit -50 | Rejected: returns `false` | 700 |
| Deposit 10,000 | Rejected: the total would exceed 10,000 | 700 |
A constructor sets up a new object. Since this class does not declare a constructor, Java supplies one with no arguments. The field starts at zero, so the invariant holds when the account is created.
Each accepted deposit keeps the balance within the limit. Each rejected deposit leaves the balance alone. The exact balance can change, but the invariant remains true.
Exercise
After the example finishes, the balance is 700 cents. What happens if the caller deposits 9,300 cents, then tries to deposit 1 cent?
Show answer
The first deposit returns true and raises the balance to 10,000 cents. The second returns false and leaves the balance at 10,000 cents.