Java Tutorial: Encapsulation
Access modifiers, private fields, getters and setters, data validation, and why hiding implementation details matters.
Protect your data
Encapsulation is one of the four pillars of OOP. By hiding internal state and controlling access through methods, you prevent invalid data from ever entering an object.
A `BankAccount` with a `public balance` field is dangerous — anyone can set it to anything. Make it `private` and only allow changes through `deposit()` and `withdraw()` — which can validate and log.
What you'll learn in this Java encapsulation tutorial
This interactive Java tutorial has 6 hands-on exercises. Estimated time: 18 minutes.
- The problem with public fields — Public fields can be set to anything — including impossible values:
- Access modifiers — Java has four access levels:
- Getters and setters — Convention for private fields:
- Immutable objects with final fields — An **immutable** object's state cannot change after construction. Make fields `final` and provide only getters — no sett…
- Builder pattern for complex objects — When a class has many optional fields, a constructor with 10 parameters is unreadable.
- Build a validated bank account — Final challenge — no starter code.
Java Encapsulation concepts covered
- Protect your data