Sub topic 1
Encapsulation: State, Behavior, and Invariants
A class is a blueprint for creating objects. An object holds data and can perform actions. Its state is its current data, stored in variables called fields. Its behavior comes from methods, which are actions the class defines.
Encapsulation means keeping an object’s state and the behavior that controls it together. It helps the object maintain an invariant: a rule that must remain true. For a bank account, one invariant might be that its balance is never negative.
Access control is one tool for encapsulation. It limits where code can use a field or method. Encapsulation is the broader goal of keeping the object’s state safe and meaningful.
A worked example
Save this code as BankAccount.java:
public class BankAccount {
private long balance;
public BankAccount(long openingBalance) {
if (openingBalance < 0) {
throw new IllegalArgumentException("Negative 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 static void main(String[] args) {
BankAccount account = new BankAccount(100);
account.deposit(50);
System.out.println(account.getBalance());
}
}A constructor sets up a new object. Here, it rejects a negative opening balance. An exception signals an error; throw reports it instead of changing the balance.
The long type stores whole numbers. The deposit method rejects negative amounts and amounts that would exceed the largest long value. The private field stops other classes from writing directly to balance.
Run the example from a terminal:
javac BankAccount.java
java BankAccountIt prints 150.
Packages and access context
A package is a named group of Java classes. Java checks where the code trying to use a field or method is located, including whether it is in the same package as the declaring class.
The example has no package declaration, so it belongs to the unnamed package.
Four access choices
An access modifier sets where code may use a class member, such as a field or method. A subclass is a class built from another class.
| Modifier | Where a member can be used |
|---|---|
| `public` | From any package, subject to other access rules |
| `protected` | In the same package and, with extra rules, in subclasses in other packages |
| No modifier | In the same package; this is called package-private access |
| `private` | Within the declaring class |
Exercise
Why does BankAccount keep balance private instead of letting other classes change it directly?
Show answer
Private access stops direct writes, so the constructor and deposit method can protect the nonnegative-balance rule.