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