About Us Contact Us Write for Us Advertise
Home > Java > Encapsulation in Java: Protecting Your Data with private, Getters and Setters
Java

Encapsulation in Java: Protecting Your Data with private, Getters and Setters

Learn encapsulation in Java — the first pillar of OOP. Use private fields with getters and setters to protect your data and validate changes, explained with simple examples.

Shiv Pandey
Shiv Pandey
Sep 21, 2026 | 3 views
Encapsulation in Java: Protecting Your Data with private, Getters and Setters

You now know how to build objects with fields and constructors. But there's a problem hiding in our earlier code: anyone could write car1.speed = -500 and put an object into a nonsensical state. Encapsulation is the OOP principle that protects against this — it's about keeping an object's data safe and letting it be changed only in controlled, sensible ways. It's the first of the four pillars of OOP, and it's a habit that separates tidy code from messy code.

The core idea: hide the data, control the access

Encapsulation has two simple parts:

  1. Make the fields private so nothing outside the class can touch them directly.
  2. Provide public methods — called getters and setters — as the controlled "doorway" to read and change those fields.

Think of it like an ATM. You can't reach into the machine and grab the cash directly (the money is private). Instead you use the buttons — a controlled interface that checks your PIN and balance first. Encapsulation gives your objects that same protective layer.

Without encapsulation (the problem)

public class BankAccount {
    public double balance;   // open to everyone!
}

// somewhere else...
account.balance = -9999;   // nothing stops this nonsense

With encapsulation (the fix)

Make the field private, then expose it through methods that can enforce rules:

public class BankAccount {
    private double balance;   // hidden — only this class can touch it

    // getter: read the value
    public double getBalance() {
        return balance;
    }

    // setter with a RULE — this is the real power
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        } else {
            System.out.println("Deposit must be positive!");
        }
    }
}

Now the outside world can't set a negative balance — the only way in is through deposit(), which checks the value first. That validation is the entire point: the object protects its own integrity.

Getters and setters

The standard pattern is a getX() to read a private field and a setX() to change it. Setters are where you put your validation rules:

public class Person {
    private String name;
    private int age;

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public int getAge() { return age; }
    public void setAge(int age) {
        if (age >= 0) this.age = age;   // no negative ages
    }
}

Using it from outside:

Person p = new Person();
p.setName("Asha");
p.setAge(28);
System.out.println(p.getName() + ", " + p.getAge());   // Asha, 28

The four access modifiers (quick reference)

Modifier Who can access it
private Only inside the same class (most protected)
public Anyone, anywhere
protected Same package + subclasses (more in later lessons)
(none) Same package only ("package-private")

The everyday rule of thumb: make fields private, make methods public (unless you have a reason not to). Simple and safe.

This is exactly how the real classes on this website are written — every entity, like a User or a Blog, keeps its fields private and exposes getters/setters. It felt like extra typing when I first learned it, but the payoff is real: when a value can only change through one guarded method, tracking down bugs becomes dramatically easier because there's only one place to look. (Modern tools and libraries like Lombok even generate these getters/setters for you — but you should understand what they're doing first.)

Key takeaways

  • Encapsulation = hide data (private fields) + control access (public getters/setters).
  • Setters let you validate changes, protecting the object from invalid states.
  • Rule of thumb: fields private, methods public.
  • It's the first pillar of OOP and the foundation of clean, maintainable classes.

← Previous: Lesson 13 — Constructors in Java
Next: Lesson 15 — Inheritance in Java →

Related Articles

Variables and Data Types in Java (Beginner's Guide)
Java

Variables and Data Types in Java (Beginner's Guide)

Constructors in Java: Setting Up Objects the Right Way
Java

Constructors in Java: Setting Up Objects the Right Way

Classes and Objects in Java: The Foundation of OOP
Java

Classes and Objects in Java: The Foundation of OOP

Strings in Java: Methods, Comparison and the equals() Trap
Java

Strings in Java: Methods, Comparison and the equals() Trap