Java OOP · Module 4
Why public fields are dangerous
The BankAccount that anyone could rob
What you'll be able to do
- Explain, with a concrete example, what goes wrong with a public field
- Write a class whose state can only change through its own methods
- Define encapsulation and data hiding in your own words
- Name three things you can do once the field is private
Encapsulation
One public field is one missing rule
`account.balance = -5000;` compiles happily. Encapsulation is how you make that line impossible.
Encapsulation means: keep the data private, and let the outside world interact with it only through methods you control. The motivation is not secrecy — it is rules. A balance must never go negative from a withdrawal, a deposit must be positive, an age cannot be −3. If the field is public, every one of those rules has to be re-checked by every caller, forever. If the field is private, the rule lives in one place: the object.
The ATM and the open cash drawer
A bank does not put the cash drawer on the pavement with a sign saying 'please only take what is yours'. It puts an ATM in front of it: you can deposit, withdraw within limits, and check your balance — and the machine refuses anything illegal. A public field is the open drawer. A private field with methods is the ATM.
The same account, two designs
public double balance
anyone can write anything
- Impossible state (negative balance) is reachable
- Validation must be repeated by every caller
- You cannot log, audit or limit changes
- Renaming or changing the field breaks all callers
private double balance
the object owns its rules
- Invalid state is unreachable from outside
- Validation exists once, inside the class
- You can log, audit, or add fees in one place
- Internals can change; the method names stay
The encapsulated BankAccount
private = usable only inside this class. Code outside cannot read *or* write it — the compiler refuses, so the mistake is caught before the program ever runs.public because the outside world needs it; a method, not a field, because a method can think.if is worth the whole design: no caller can bypass it.Run it, then add `account.balance = 1000000;` and read the compiler error — that error message is encapsulation doing its job.
The default you should adopt today
Make every field private and expose only the methods callers genuinely need. Then relax that only when you have a reason. Professional Java code follows this almost without exception — and interviewers expect you to state it as a habit, not a rule you memorised.
Prove it — coding challenges
Data Hiding
Data hiding: what you gain once the field is private
Four powers you only have behind a private field
- Validation: refuse impossible values in one place (
amount <= 0). - Invariants: keep related fields consistent — update
balanceand append a transaction together, never one without the other. - Freedom to change internals: store cents as a
longtomorrow; callers still callgetBalance()and never notice. - Observability: log, audit, count or rate-limit every change, because every change goes through your method.
Encapsulation vs abstraction — the interview distinction
They are cousins, not twins. Encapsulation hides *data* and protects it behind behaviour (private balance + deposit). Abstraction hides *implementation* behind a simplified contract (interface PaymentMethod { void pay(double amount); }, Modules 10–11). One protects state; the other simplifies design. Say that sentence in an interview and you are ahead of most candidates.
Common mistakes
private double balance; public double getBalance() {...} public void setBalance(double b) { balance = b; }Validating in main before calling deposit.Thinking `private` protects against hackers.Lesson playground
Add a `withdraw(double amount)` method that refuses amounts larger than the balance, then try to withdraw too much.
Check understanding
Quiz
Question 1 of 4
Two withdrawals, one too large. What is printed?
Summary
- Encapsulation = private data + public behaviour that enforces the rules.
- A public field means every caller must remember every rule; a private field means the object remembers.
- Reject invalid input without changing state — never leave the object half-updated.
- Private fields let internals change without breaking callers.