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.
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.