Skip to content
Qyubie Learn
Java tutorialLesson 12 of 18 · tap to see all lessons

Java tutorial · Beginner

Java Encapsulation: private Fields, Access Modifiers, Getters, and Setters

Protect an object's data in Java with private fields, the four access levels, getter and setter methods, and validation that keeps every object valid.

  • Qyubie Learn Editorial Team
  • Published
  • 7 min read

Includes 2 quick checks you can do right here.

So far, any code could reach into an object and change its fields: acc.balance = -5000; compiles without complaint. In a real system, that's how bugs and fraud happen. Encapsulation, the first pillar of OOP, means hiding an object's data and letting other code change it only through methods that follow the rules.

By the end of this lesson you will be able to:

  • explain data hiding and why it matters,
  • use the four access levels: private, package-private, protected, and public,
  • write getter and setter methods, and
  • validate data in setters so objects stay valid.

The problem: open fields

class Account {
    String owner;
    double balance;
}

public class Main {
    public static void main(String[] args) {
        Account acc = new Account();
        acc.owner = "Ana";
        acc.balance = -5000;          // nothing stops this
        System.out.println(acc.owner + ": " + acc.balance);
    }
}

Output:

Ana: -5000.0

The class has no way to protect itself. Every piece of code that uses Account has to remember the rules ("balance can't be negative"), and one forgotten check corrupts the data.

The fix: private fields and public methods

Mark the fields private so only code inside the class can touch them. Then provide public methods that apply the rules:

class Account {
    private String owner;
    private double balance;

    public Account(String owner) {
        this.owner = owner;
    }

    public void deposit(double amount) {
        if (amount <= 0) {
            System.out.println("Deposit must be positive");
            return;
        }
        balance += amount;
    }

    public boolean withdraw(double amount) {
        if (amount <= 0 || amount > balance) {
            System.out.println("Withdrawal of " + amount + " refused");
            return false;
        }
        balance -= amount;
        return true;
    }

    public double getBalance() {
        return balance;
    }
}

public class Main {
    public static void main(String[] args) {
        Account acc = new Account("Ana");
        acc.deposit(1000);
        acc.withdraw(1500);
        acc.withdraw(300);
        acc.deposit(-50);
        System.out.println("Balance: " + acc.getBalance());
        // acc.balance = -5000;   // error: balance has private access in Account
    }
}

Output:

Withdrawal of 1500.0 refused
Deposit must be positive
Balance: 700.0

Now the only ways to change the balance are deposit and withdraw, and both check the rules. The class guards its own data, so the rest of the program can't break it.

The four access levels

Java has four levels of access. The most important are private and public.

ModifierSame classSame packageSubclass (other package)Everywhere
private✓
(none) package-private✓✓
protected✓✓✓
public✓✓✓✓
  • private: only inside the class. Use it for fields.
  • package-private (no keyword): visible to classes in the same package (folder). This is what you get when you forget to write a modifier.
  • protected: the package, plus subclasses anywhere. You'll use it with inheritance in lesson 17.
  • public: visible everywhere. Use it for the methods other classes should call.

A good default: fields private, methods public, and make a helper method private if only the class itself uses it.

Quick check

A field is declared with no access modifier: double rate;. Who can access it?

Getters and setters

For fields that other classes need to read or change, write a getter (getX) that returns the value, and a setter (setX) that changes it. These are the naming conventions every Java tool expects.

class Student {
    private String name;
    private double gwa;

    public Student(String name, double gwa) {
        this.name = name;
        setGwa(gwa);                 // reuse the setter's check
    }

    public String getName() {
        return name;
    }

    public double getGwa() {
        return gwa;
    }

    public void setGwa(double gwa) {
        if (gwa < 1.0 || gwa > 5.0) {
            System.out.println("Invalid GWA " + gwa + " ignored");
            return;
        }
        this.gwa = gwa;
    }
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student("Ana", 1.75);
        s.setGwa(7.0);
        s.setGwa(1.5);
        System.out.println(s.getName() + ": " + s.getGwa());
    }
}

Output:

Invalid GWA 7.0 ignored
Ana: 1.5

Notes:

  • For a boolean field, the getter is usually named isX(), for example isEnrolled().
  • Validation lives in the setter, and the constructor calls the setter, so the check is written once and applies everywhere.
  • You don't need a setter for every field. Here name has no setter, so it can't be changed after the student is created; it's read-only. Leaving out setters is a deliberate design choice.

Quick check

What does this print?
class Temp {
    private int celsius;
    public void setCelsius(int c) {
        if (c >= -50 && c <= 60) celsius = c;
    }
    public int getCelsius() { return celsius; }
}
public class Main {
    public static void main(String[] args) {
        Temp t = new Temp();
        t.setCelsius(30);
        t.setCelsius(100);
        System.out.println(t.getCelsius());
    }
}

Why bother? A summary of the benefits

  • Valid data: objects can't be put into an impossible state, like a negative balance or a GWA of 7.0.
  • Freedom to change the inside: you could store the balance in centavos as a long and change only the class; code that calls getBalance() keeps working.
  • Easier debugging: if a field gets a wrong value, only the class's own methods could have set it.
  • Read-only and write-only data: you choose what to expose by which getters and setters you write.

Common mistakes

  • Leaving fields public (or with no modifier) "for convenience."
  • Setters that don't check anything, which give you encapsulation in name only. Add validation where the data has rules.
  • A constructor that sets fields directly while the setter validates, so invalid values can sneak in through the constructor. Call the setter from the constructor.
  • Getters that return a private array, which lets callers change its contents. Return a copy for important data.
  • Writing getname(). The convention is getName(): get plus the field name with its first letter capitalized.

Summary

  • Encapsulation hides an object's data (private fields) and exposes behavior through public methods.
  • Access levels, from most to least restricted: private, package-private (no keyword), protected, public.
  • Getters (getX, or isX for booleans) read fields; setters (setX) change them, and should validate.
  • Leaving out a setter makes a field read-only from outside.

Next lesson: method overloading and object interaction: objects calling each other and building larger objects from smaller ones.

References and further reading