Introduction: A Balance of Minus Five Million
Your account balance is 100,000 rupiah. Then, somewhere else in the program, there is one line of code:
r.saldo = -5_000_000;
Nothing stops it.
In real life, your money is kept in a vault, not on an open table. In this part we build a vault for objects. It is called encapsulation.
After this part, you will be able to:
- Lock a field with
private. - Open a "counter" with a
publicmethod, with its own rules. - Organise a program with one class in one file.
Answer to the Part 13 Challenge
The question: b = a, then b[0] is changed to 99. What does a[0] print?
The answer is C: 99.
An array is also an object, so it is made in the warehouse. b = a only copies the ticket, so a and b point to the same row of lockers. Changing it through b changes it for a too.
If you answered C, well done!
1. The Problem: Anyone Can Change Anything
So far, anyone can change the fields of an object directly. rekening.saldo = ... can be set to anything. (Rekening means "bank account" and saldo means "balance".)
In a small program, that feels handy. In a big program with dozens of programmers, one careless line can break data everywhere. And then it is hard to find out who did it.
2. Encapsulation Is a Vault and a Counter
Picture a bank.
- The money is kept in a locked vault. Customers cannot walk in and take money themselves.
- Everything goes through the service counter. Want to deposit? The clerk checks the amount. Want to withdraw? The clerk checks whether the balance is enough.
In Java:
| At the bank | In Java |
|---|---|
| The locked vault | A field marked private |
| The service counter | A method marked public |
| The clerk's rules | The if inside that method |
This idea is called encapsulation.
Click the diagram to open it in full size.
3. From Now On: One Class, One File
Before we write the code, there is one important point.
In the short-version file we have used so far, every class lives in the same house as main. Inside one house, the private lock does not work between them. So the vault would not feel locked.
That is why, from this part on, we use the way people work in real jobs: one class, one file.
Create a new folder and put two files in it:
| File | Content |
|---|---|
Rekening.java | The Rekening class |
Main.java | void main() |
Run it with:
java Main.java
Java finds Rekening.java in the same folder by itself.
4. Building the Vault and Its Counters
The file Rekening.java:
public class Rekening {
private int saldo;
public int getSaldo() {
return saldo;
}
public void setor(int uang) {
if (uang > 0) {
saldo += uang;
}
}
public boolean tarik(int uang) {
if (uang > 0 && uang <= saldo) {
saldo -= uang;
return true;
}
return false;
}
}
Setor means "deposit", tarik means "withdraw", and uang means "money".
| Piece | Meaning |
|---|---|
private int saldo; | The vault. Only code inside the Rekening class may touch saldo. |
getSaldo() | The counter for reading the balance. A method like this is called a getter. |
setor(...) | The deposit counter. It only adds to the balance when the amount is more than zero. |
tarik(...) | The withdraw counter. It only takes money when the balance is enough, then answers true or false. |
public | Can be used from other classes, for example from Main. |
The file Main.java:
void main() {
Rekening r = new Rekening();
r.setor(100_000);
r.setor(-50_000);
IO.println("Saldo: " + r.getSaldo());
IO.println("Tarik 250.000: " + r.tarik(250_000));
IO.println("Tarik 30.000: " + r.tarik(30_000));
IO.println("Saldo: " + r.getSaldo());
}
Saldo: 100000
Tarik 250.000: false
Tarik 30.000: true
Saldo: 70000
The clerk rejects the negative deposit, so the balance stays 100,000. Withdrawing 250,000 is rejected because the balance is not enough. Withdrawing 30,000 is accepted, and the balance becomes 70,000.
And what if Main tries this?
void main() {
Rekening r = new Rekening();
r.saldo = -5_000_000;
}
Main.java:3: error: saldo has private access in Rekening
r.saldo = -5_000_000;
^
1 error
error: compilation failed
javac rejects it at once. The vault is locked. The only way in is through a counter.
5. A Real Example: A Login Account
The file Akun.java. Akun means "account" and sandi means "password".
public class Akun {
private String nama;
private String sandi;
public Akun(String nama, String sandi) {
this.nama = nama;
this.sandi = sandi;
}
public String getNama() {
return nama;
}
public boolean cekSandi(String tebakan) {
return sandi.equals(tebakan);
}
}
The file Main.java:
void main() {
Akun akun = new Akun("rani", "kopi123");
IO.println(akun.getNama());
IO.println(akun.cekSandi("teh456"));
IO.println(akun.cekSandi("kopi123"));
}
rani
false
true
Notice that we chose not to write a getter for sandi. There is only cekSandi ("check password"). It takes a guess (tebakan), compares it with .equals() from Part 13, and answers true or false.
So the rest of the program can check the password without ever being able to read it.
Encapsulation is not just writing a getter and a setter for every field. You decide which counters to open.
A note: this is an example for learning. A real app does not store a password as it is. It stores it in a scrambled form called a hash.
6. Three Encapsulation Traps
Trap one: making a field public because it is handy.
Once it is public, anyone can change it. The rules at the counter become useless, because people can go straight through the back door.
Trap two: a setter with no checks.
public void setSaldo(int saldo) {
this.saldo = saldo;
}
A setter that accepts any value is the same as leaving the vault open. Put your rules inside the setter.
Trap three: testing private in a short-version file.
class Rekening {
private int saldo;
}
void main() {
Rekening r = new Rekening();
r.saldo = -5_000_000;
IO.println(r.saldo);
}
-5000000
There is no error. Because every class lives in the same house as main, the private lock is not felt. Put each class in its own file, as in section 3.
Summary
- Encapsulation means keeping data in a
privatevault and openingpubliccounters. - A getter is for reading. A setter or another method is for changing, with the rules inside it.
- One class, one file. A
privatefield can only be touched from its own class.
Challenge
The file Lampu.java. Lampu means "lamp" and terang means "brightness".
public class Lampu {
private int terang = 50;
public int getTerang() {
return terang;
}
public void setTerang(int nilai) {
if (nilai >= 0 && nilai <= 100) {
terang = nilai;
}
}
}
The file Main.java:
void main() {
Lampu lampu = new Lampu();
lampu.setTerang(120);
lampu.setTerang(80);
lampu.setTerang(-10);
IO.println(lampu.getTerang());
}
What is the output?
- A.
-10 - B.
80 - C.
50
Try to answer before you run it. I explain the answer at the start of Part 15.
Conclusion & What's Next
The objects you build now have a vault. If you remember only one thing, remember the bank: the data stays in the vault, and everyone goes through a counter that has rules.
In Part 15, our cutter gets a child: a new cutter that inherits every shape of its parent, then adds its own decoration.
See you in Part 15. Get your coffee ready. Hot chocolate is fine too.

Written by Muhammad Fari Madyan
Senior Backend Engineer and co-founder of LampungDev. I write up what I build so others can learn from it.

