OOP and design · Topic 2 of 12
Encapsulation
Definition​
Encapsulation means keeping an object's data private and letting other code change it only through methods. The object can then protect its own rules, so it never ends up in an invalid state.
Example code​
A bank account that protects its balance
class BankAccount {
private long balanceCents; // hidden: nobody can set it directly
void deposit(long cents) {
if (cents <= 0) throw new IllegalArgumentException("Deposit must be positive");
balanceCents += cents;
}
void withdraw(long cents) {
if (cents > balanceCents) throw new IllegalStateException("Not enough money");
balanceCents -= cents;
}
long balance() { return balanceCents; }
}
class Demo {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(5_000);
account.withdraw(1_200);
System.out.println(account.balance());
try {
account.withdraw(10_000);
} catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
}
}
// Output:
// 3800
// Not enough money
Finished this page? Track your progress (saved only in your browser).