Skip to content

Java OOP

0/36 lessons · 0% complete

— XP

Java OOP · Module 4

Why public fields are dangerous

The BankAccount that anyone could rob

18m50 XP
→→→

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
1

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

Main.java
1account.balance = -5000;
2account.balance = account.balance + 100;
3// where is the rule?
4// who logged this change?
  • 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

Main.java
1account.deposit(100);
2account.withdraw(5000); // refused
3double b = account.getBalance();
  • 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

Main.java
1class BankAccount {
2 private double balance;
3
4 public void deposit(double amount) {
5 if (amount <= 0) {
6 System.out.println("Deposit must be positive");
7 return;
8 }
9 balance = balance + amount;
10 }
11
12 public double getBalance() {
13 return balance;
14 }
15}
private double balance;
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 void deposit(double amount) {
The controlled door in. public because the outside world needs it; a method, not a field, because a method can think.
if (amount <= 0) {
The rule. This single if is worth the whole design: no caller can bypass it.
return;
Reject and leave the state untouched. An invalid request changes nothing — the object is never half-updated.
balance = balance + amount;
Only reached for valid input. Inside the class the private field is fully accessible.
public double getBalance() {
A read-only window. The outside can *see* the balance but has no way to *set* it — that asymmetry is the point.
Try to break the account

Run it, then add `account.balance = 1000000;` and read the compiler error — that error message is encapsulation doing its job.

Output
Press Run to execute this example.

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

2

Data Hiding

Data hiding: what you gain once the field is private

Four powers you only have behind a private field

  1. Validation: refuse impossible values in one place (amount <= 0).
  2. Invariants: keep related fields consistent — update balance and append a transaction together, never one without the other.
  3. Freedom to change internals: store cents as a long tomorrow; callers still call getBalance() and never notice.
  4. 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.

What the compiler says when you try
Main.java
1BankAccount account = new BankAccount();
2account.balance = 1000000;
3// error: balance has private access in BankAccount
A compile-time error, not a runtime surprise: the mistake cannot reach production.

Common mistakes

Wrongprivate double balance; public double getBalance() {...} public void setBalance(double b) { balance = b; }
WhyA setter with no rules is a public field with extra typing — `setBalance(-5000)` is still possible.
FixExpose intent-revealing behaviour instead: `deposit(...)`, `withdraw(...)`, each with validation.
WrongValidating in main before calling deposit.
WhyThe next caller — or the next screen, or the next developer — will forget.
FixPut the rule inside the method so it cannot be skipped.
WrongThinking `private` protects against hackers.
WhyIt is a compile-time design tool, not a security boundary.
FixUse it to protect *correctness*; use real security tooling for security.

Lesson playground

Free practice

Add a `withdraw(double amount)` method that refuses amounts larger than the balance, then try to withdraw too much.

Output
Press Run to execute this example.

Check understanding

Quiz

Question 1 of 4

Two withdrawals, one too large. What is printed?

Main.java
1class BankAccount {
2 private double balance;
3
4 public void deposit(double amount) {
5 if (amount <= 0) {
6 return;
7 }
8 balance = balance + amount;
9 }
10
11 public boolean withdraw(double amount) {
12 if (amount > balance) {
13 return false;
14 }
15 balance = balance - amount;
16 return true;
17 }
18
19 public double getBalance() {
20 return balance;
21 }
22}
23
24public class Main {
25 public static void main(String[] args) {
26 BankAccount a = new BankAccount();
27 a.deposit(200);
28 a.deposit(-50);
29
30 System.out.println(a.withdraw(500));
31 System.out.println(a.withdraw(150));
32 System.out.println(a.getBalance());
33 }
34}

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.