Concept · Intro

Encapsulation

Bundle data with the methods that guard it, hide the internals, and expose only a safe public interface — so invariants can’t be broken.

Asked atAmazonMicrosoftBloomberg
step 1 / 9
1/2The capsule
BankAccount
- balance: int
- pin: String
+ deposit(amt)
+ withdraw(amt)
+ getBalance()
The capsule
1class BankAccount {
2 private int balance;
3 private String pin;
4 
5 public void deposit(int amt) { ... }
6 public void withdraw(int amt) {
7 if (amt > balance) throw new Error();
8 balance -= amt;
9 }
10 public int getBalance() { return balance; }
11}
State
private (hidden)

Here is one capsule: BankAccount. The middle rows are its data — balance and pin — each marked with a “−”. That dash means PRIVATE: locked away, unreachable from outside.