๐ฏ What you will learn
Raw public fields are one of the most common sources of bugs in Java codebases. Encapsulation fixes that by hiding state and enforcing invariants at the point of change. By the end of this lesson you will understand:
- What encapsulation means and why it matters in production
- The four access modifiers โ
private, package-private,protected,public - How to write validated getters and setters
- Java 16 records โ compact immutable data carriers
- When to use a record vs a regular class
๐ What is encapsulation?
Encapsulation means bundling data (fields) and behaviour (methods) together and hiding the internal representation from the outside. In Java: make fields private, expose controlled access via public getters/setters that can validate. The caller never sees the field; it sees only the interface.
This means you can change the internal representation later โ say, storing income in paise instead of rupees โ without changing the public API. Callers are insulated from implementation details.
| Modifier | Same class | Same package | Subclass | Everywhere |
|---|---|---|---|---|
private | โ | โ | โ | โ |
| (package) | โ | โ | โ | โ |
protected | โ | โ | โ | โ |
public | โ | โ | โ | โ |
๐งพ Real-world scenario
TaxSetu processes payroll for 12,000 employees. Meera, a backend engineer, was burned last quarter when a negative income value slipped through a CSV import and produced a tax refund instead of a liability. Now she enforces invariants directly in the class: PAN must be 10-char alphanumeric, income must be non-negative, age must be between 18 and 120. The field is private; the setter validates before accepting.
๐ก๏ธ Validated getters and setters
The constructor delegates to the setters so validation runs both at construction time and on subsequent updates. Invalid values throw IllegalArgumentException immediately โ the object is never in a corrupt state.
Design note: The constructor calls setPan(), setAnnualIncome(), and setAge() โ not the fields directly. This ensures there is one source of truth for validation and avoids duplicating rules.
๐ Access modifiers in action
The following example shows all four access levels on fields and methods. Notice that cashReserve (private) is only reachable through the public getter โ direct field access would be a compile error from outside the class.
๐ Java 16 records โ compact immutable data carriers
A record is a concise way to declare an immutable data class. The compiler auto-generates: a canonical constructor, field accessors (no get prefix โ meera.name() not meera.getName()), equals(), hashCode(), and toString(). Fields are private final โ no setters.
A compact constructor (no parameter list) is a convenient place to add validation โ it runs before the fields are assigned.
Records quick-reference: Records auto-generate: canonical constructor, accessors (no get prefix: meera.name()), equals(), hashCode(), toString(). Fields are private final. Records cannot extend classes (they implicitly extend Record). They can implement interfaces. Compact constructor (no params) runs validation.
๐ค Interview Q&A
Encapsulation is hiding internal state and exposing only controlled access. Private fields with validated setters enforce invariants โ bad values are rejected before they corrupt state. It also lets you change the internal representation later (e.g., store income in paise instead of rupees) without changing the public API.
A record is a concise, immutable data carrier. It auto-generates a canonical constructor, field accessors (name() not getName()), equals(), hashCode(), and toString(). Fields are private final โ no setters. A regular class is mutable by default and requires you to write everything manually. Use records for DTOs and value objects; use classes when you need mutation or inheritance.
protected access wider than many developers expect?protected grants access to: the class itself, all classes in the same package (regardless of inheritance), and all subclasses in any package. Developers often think it means "subclasses only" โ but the package-private component means classes in the same package that are not subclasses can also access protected members. This is why sensitive logic should often stay private even in hierarchies.
Constructor validation runs once at object creation and guarantees the object is always valid from birth โ great for immutable objects. Setter validation allows updating individual fields later but requires each setter to re-validate. If an object can change after creation, both constructor and setter must validate. Records put validation in the compact constructor, covering both scenarios since records are immutable.
OCP (the O in SOLID) states: open for extension, closed for modification. Encapsulation supports OCP โ by hiding internal details, you can change the implementation (open) without changing the public interface (closed). For example, changing taxLiability() from simple slab calculation to a DB-driven lookup doesn't break any caller, because the field is private and the method signature is unchanged. Exposing fields publicly breaks OCP โ callers would depend on the internal representation.
๐ Quiz โ 5 questions
private field โ can a subclass access it directly?Next: Collections โ
โ ๏ธ Common mistakes
public double balance means any code can set obj.balance = -999. Always make fields private and control access through setters with validation.return this if you want profile.setPan(...).setAge(...) โ the builder pattern for fluent APIs.protected is also visible to all classes in the same package, not just subclasses. This is broader than most developers expect โ keep sensitive logic private.final. If your object needs to change after construction, use a regular class. Records shine for DTOs, value objects, and response models.โ Key takeaways
- Make fields
privateand expose controlled access through validated getters/setters. privateโ class only; package-private โ package;protectedโ package + subclasses;publicโ everywhere.- Validation in setters enforces invariants at the point of change.
- Java 16 records are compact immutable data carriers โ auto-generate boilerplate.
- Encapsulation = internal representation can change without breaking the public API.
From encapsulation to production Spring Boot
Join the Best AI Programs โ three 5-month courses, fully online, with placement assistance. Week 1 is free.
Explore our AI-era courses โ