Sub topic 1
Encapsulation: State, Behavior, and Invariants
An object often needs to remember information and change it over time. A bank account, for example, remembers a balance. Deposits and withdrawals change that balance.
Encapsulation is the practice of keeping an object’s data and the operations that work on it together, while controlling how other code uses them. It helps the object stay in a valid state.
In this chapter, you will build a small account example and use it to see how encapsulation protects a rule about its balance.
State and behavior
A class is a plan for creating objects. An object is a particular item created from a class. A BankAccount class, for example, can describe many account objects. Each account can have its own balance.
An object’s state is the information it holds at a particular time. A field is a named place inside an object where it stores information. An account might have a balance field.
A method is a named action that code can ask an object to perform. An object’s behavior is what it can do through its methods. An account might have methods to deposit money, withdraw money, and report its balance.
State can change while the object stays the same object. If an account starts with a balance of 100 and receives a deposit of 50, its balance becomes 150. A different account object is not affected.
| Idea | Question it answers | Account example |
|---|---|---|
| State | What information does the object hold now? | The balance is 150. |
| Behavior | What can the object do? | Accept a deposit or withdrawal. |
| Class | What kind of object is this? | A BankAccount. |
What is an invariant?
An invariant is a rule that must remain true about an object whenever it is in a valid state.
For our example, the account has this invariant:
- The balance is at least 0 and at most 1,000 whole dollars.
The exact balance can change. It might be 100 now and 150 later. Both values satisfy the rule. A balance of -20 or 1,100 does not.
The upper limit is a rule chosen for this teaching example. It is not a general banking rule. The example also uses whole dollars to keep the arithmetic simple.
An invariant must hold when the object is created. It must also hold after an operation changes the object. If an operation cannot make a valid change, the object should not accept that change.
An operation can have other rules too. For example, our account accepts only positive deposit amounts. A deposit of 0 would leave the balance within its allowed range, but the operation still rejects it. The positive-amount rule describes which deposits are allowed; the balance invariant describes which account states are valid.
Why encapsulation matters
Suppose any code that uses an account could set its balance directly. One part of a program might set it to -20 by mistake. Another part might assume the balance is never negative and make a decision using bad information.
Encapsulation gives the account a place to enforce its own rule. Code using the account asks it to perform an operation. The account checks the request before changing its balance.
This gives responsibilities to both sides:
- The caller is the code that asks an object to perform a method.
- The account checks whether the requested change is allowed.
- The account keeps its balance within the invariant.
- The caller can rely on the account’s valid balance when using the shown operations.
This arrangement also gives the account a clear boundary. Other code can ask for a deposit without needing to perform the balance check itself. The rule lives with the data it protects.
Encapsulation and access control
Access control is Java’s way of limiting where code may use a declaration, such as a field or method. An access modifier is a keyword that helps set that limit.
In the example:
- Private restricts direct use of the balance field to the account’s own code.
- Public allows callers to use the account’s methods, subject to access to the class itself.
These keywords support encapsulation, but they are not the whole idea. A private balance is not enough if a public method can set it to a negative number. The methods must also preserve the invariant.
The reverse is true as well: a field might happen to hold a valid value, but if other code can freely change it, the account cannot reliably protect that value. Encapsulation combines a boundary with behavior that maintains the object’s rules.
Worked example: an account
The following program defines an account and then uses one. Its balance is an integer: a whole number with no fractional part.
A constructor is the part of a class that sets up a new object. The BankAccount constructor checks the opening balance. The methods then check deposits and withdrawals before changing the balance.
An exception is a signal that an operation could not proceed normally. Here, the account throws an IllegalArgumentException when it receives an amount it cannot accept. The word “throws” means that the method reports the problem instead of completing the requested change.
Save this program in a file named AccountDemo.java:
public class AccountDemo {
public static void main(String[] args) {
BankAccount account = new BankAccount(100);
System.out.println("Balance: " + account.getBalance());
account.deposit(50);
System.out.println("After deposit: " + account.getBalance());
account.withdraw(30);
System.out.println("After withdrawal: " + account.getBalance());
try {
account.withdraw(200);
} catch (IllegalArgumentException problem) {
System.out.println("Could not withdraw: " + problem.getMessage());
}
System.out.println("After failed withdrawal: " + account.getBalance());
}
}
class BankAccount {
private int balance;
public BankAccount(int openingBalance) {
if (openingBalance < 0 || openingBalance > 1000) {
throw new IllegalArgumentException("Opening balance out of range");
}
balance = openingBalance;
}
public int getBalance() {
return balance;
}
public void deposit(int amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Deposit must be positive");
}
if (amount > 1000 - balance) {
throw new IllegalArgumentException("Balance limit exceeded");
}
balance += amount;
}
public void withdraw(int amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Withdrawal must be positive");
}
if (amount > balance) {
throw new IllegalArgumentException("Not enough money");
}
balance -= amount;
}
}To run it, you need a Java Development Kit, or JDK: the tools used to compile and run Java programs. Open a terminal in the folder containing AccountDemo.java, and run:
javac AccountDemo.java
java AccountDemoThe first command compiles the program, which means it turns the Java source code into a form Java can run. The second command runs it. The output is:
Balance: 100
After deposit: 150
After withdrawal: 120
Could not withdraw: Not enough money
After failed withdrawal: 120Follow the balance
Let’s trace what happens to the account’s state.
- The constructor receives an opening balance of 100. That value is within the allowed range, so the account starts with a balance of 100.
- The deposit method receives 50. The amount is positive, and adding it will not take the balance above 1,000. The new balance is 150.
- The withdraw method receives 30. The amount is positive and no greater than the balance. The new balance is 120.
- The next withdrawal asks for 200. That is more than the available 120, so the method throws an exception before changing the balance.
- The final balance is still 120.
The invariant holds at every completed step: the balance remains between 0 and 1,000.
The program uses a try block to attempt the last withdrawal. A catch block handles the exception if that withdrawal fails. In this example, handling the exception lets the program print the reason for failure and then show that the balance did not change.
If the opening balance were negative or above 1,000, the constructor would throw an exception instead of completing the creation of an account. That prevents the program from receiving a newly created account with an invalid starting balance.
How the object protects its state
Notice where the balance changes: inside BankAccount. The caller uses deposit and withdraw rather than directly assigning a new balance.
The getBalance method lets the caller read the balance. It returns an integer value; changing a separate integer variable in the caller would not change the account’s field. Reading the balance is different from gaining the ability to write a new balance into the account.
Each changing method checks its request before its final balance change. The deposit method checks both that the amount is positive and that it fits below the limit. It uses 1,000 minus the current balance to find the remaining room. The withdrawal method checks that the amount is positive and no greater than the current balance.
Because the checks come before the changes, the rejected withdrawal in the example leaves the balance untouched. That is useful behavior for a caller: a failed request does not leave behind a partial change.
Think in terms of valid states
When you design a class, ask what must always be true about each object. Start with a rule that describes the data, not a particular sequence of actions.
For example:
- A counter’s value might need to stay at or above zero.
- A rectangle’s width and height might each need to be positive.
- A temperature setting might need to stay within a device’s supported range.
Then consider the object’s behavior. How could an operation move the object from one valid state to another? What request should it reject because the result would break a rule?
For the account, both a deposit and a withdrawal can be valid actions. Their results depend on the current balance and the requested amount. A withdrawal of 30 is valid when the balance is 150, but it would not be valid when the balance is 20.
This is the value of keeping the rule with the account. The caller does not need to know every detail of how the balance is stored. It asks the account to act, and the account is responsible for checking the request.
Exercise
An account has a balance of 800. Is a deposit of 250 allowed by the example’s rules? What happens to the balance?
Show answer
No. The result would exceed 1,000, so the deposit throws an exception and the balance remains 800.
Exercise
Why would making the balance private be insufficient if the deposit method accepted negative amounts?
Show answer
A negative deposit could reduce the balance below zero. Private access limits direct writes, but the method must also check requests to preserve the invariant.
Exercise
An account has a balance of 40. It accepts a withdrawal of 40. Does the resulting state satisfy the invariant?
Show answer
Yes. The balance becomes 0, which is within the allowed range of 0 through 1,000.