Java Encapsulation & Modifiers

private fields, getters and setters.

✍️ 2 exercises in this lesson

Encapsulation hides an object's data and exposes it only through methods.

Access modifiers

  • public: accessible everywhere.
  • private: only inside the class.
  • protected: the package and subclasses.
  • (no modifier): only within the same package.

Make fields private and provide getters and setters that can validate values.

For simple data carriers, Java 16+ record classes generate the constructor, getters, equals and toString for you.

Key Takeaways: Java Encapsulation & Modifiers

Mastering Java Encapsulation & Modifiers helps you write clean and reliable Java code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Java Encapsulation & Modifiers Code Example

Java
class Account {
    private double balance;

    public double getBalance() { return balance; }

    public void deposit(double amount) {
        if (amount <= 0) throw new IllegalArgumentException("Amount must be positive");
        balance += amount;
    }
}

record Point(int x, int y) {}

public class Main {
    public static void main(String[] args) {
        Account acc = new Account();
        acc.deposit(1500);
        System.out.println(acc.getBalance());

        Point p = new Point(3, 4);
        System.out.println(p + " x=" + p.x());
    }
}
Output
1500.0
Point[x=3, y=4] x=3
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

Java Encapsulation & Modifiers Practice Exercises

Check what you learned in “Java Encapsulation & Modifiers”.

/ 2 solved
Fill in the blank

Hide the field from other classes.

 double balance;
✓ Correct! Not quite. Try again.
Multiple choice

What do getters and setters provide?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services