← Back to Week 2 Hub

Encapsulation: public vs private

Why fields are private, how getters and setters control access, and the wall that protects your data.

Section 1 — The Black Box
BankAccount
Outside Code (public access)
🔑 deposit(amount)
🔑 withdraw(amount)
🔑 getBalance()
Access Wall
Inside the Object (private)
🔒 double balance
🔒 String accountNumber
🔒 String pin
Tip: Public methods are like buttons on an ATM — you can press them from outside. Private fields are the money and wiring inside — you can't reach in and grab them directly.
Section 2 — Interactive Access Test
BankAccount account = new BankAccount("12345", 1000.00);
// Click each line to see if it compiles:
account.balance = 5000; Click to try
account.getBalance(); Click to try
account.deposit(500); Click to try
account.accountNumber = "99999"; Click to try
account.withdraw(200); Click to try
Tested: 0 / 5
Section 3 — Why Encapsulate?
❌ Without Encapsulation
// Anyone can set invalid values! account.balance = -999999; account.pin = ""; account.accountNumber = null;
No protection. Any code can set any value — even ones that make no sense. A negative balance? An empty PIN? Total chaos.
✅ With Encapsulation
public void withdraw(double amount) { if (amount > 0 && amount <= balance) { balance -= amount; // Validated! } }
The method validates before changing the field. Negative amounts? Rejected. Overdraft? Blocked. The object protects itself.
Key Idea: Making fields private isn't about hiding data — it's about controlling how data gets changed. The object decides what's valid, not the outside code.
Section 4 — The Getter / Setter Pattern
🔒
Private Field
private double balance;
👁
Getter (Read)
public double getBalance() { return this.balance; }
✏️
Setter (Write)
public void setBalance(double balance) { this.balance = balance; }
READ PATH (Getter)
Outside Code
getBalance()
balance value
Returns to caller
WRITE PATH (Setter / Method)
Outside Code
setBalance() / withdraw()
Validation
Field Updated
Tip: In Java, we make fields private and provide public getters and setters. This is the standard pattern you'll use in every class.

Click each line in Section 2 to test whether it compiles or crashes.

← Classes & Objects: Blueprint vs Instance Constructor Overloading →