Muhammad Fari Madyan
Hire me
Java basics · part 14 of 21

Learn Java from Scratch Part 14: Encapsulation — private, Getters & One Class per File

The fourteenth part of a Java series: encapsulation as a bank vault and counter, private fields and public methods, getters and setters with rules, one class per file with java Main.java, a login account, and three traps such as a setter with no checks.

Muhammad Fari Madyan

· 7 min read

Baca dalam Bahasa Indonesia →

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:

JAVA
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:

  1. Lock a field with private.
  2. Open a "counter" with a public method, with its own rules.
  3. 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 bankIn Java
The locked vaultA field marked private
The service counterA method marked public
The clerk's rulesThe if inside that method

This idea is called encapsulation.

Encapsulation is like a bank: private fields inside the vault, public methods as counters with rules

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:

FileContent
Rekening.javaThe Rekening class
Main.javavoid main()

Run it with:

BASH
java Main.java

Java finds Rekening.java in the same folder by itself.


4. Building the Vault and Its Counters

The file Rekening.java:

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

PieceMeaning
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.
publicCan be used from other classes, for example from Main.

The file Main.java:

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());
}
TEXT
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?

JAVA
void main() {
    Rekening r = new Rekening();
    r.saldo = -5_000_000;
}
TEXT
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".

JAVA
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:

JAVA
void main() {
    Akun akun = new Akun("rani", "kopi123");

    IO.println(akun.getNama());
    IO.println(akun.cekSandi("teh456"));
    IO.println(akun.cekSandi("kopi123"));
}
TEXT
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.

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

JAVA
class Rekening {
    private int saldo;
}

void main() {
    Rekening r = new Rekening();
    r.saldo = -5_000_000;
    IO.println(r.saldo);
}
TEXT
-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

  1. Encapsulation means keeping data in a private vault and opening public counters.
  2. A getter is for reading. A setter or another method is for changing, with the rules inside it.
  3. One class, one file. A private field can only be touched from its own class.

Challenge

The file Lampu.java. Lampu means "lamp" and terang means "brightness".

JAVA
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:

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.

ShareLinkedInXWhatsApp

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.

Work with me
← part 13Stack, Heap and Referencespart 15 →Inheritance

Muhammad Fari Madyan

Senior Backend Engineer building real-time, high-concurrency systems that hold up in production. Co-founder of LampungDev. Based in Bandar Lampung, Indonesia (UTC+7), working remote.

Work

Case studiesCahTixExam platform, 4 stacksOpen source

© 2026 Muhammad Fari Madyan

Designed and built by Muhammad Fari Madyan