Learning Objectives
- Differentiate a class blueprint from heap-allocated object instances.
- Enforce class invariants inside constructors and domain methods instead of exposing public mutable fields.
- Apply Java 17+ `record` types cleanly for immutable value objects and DTOs.
Prerequisites
- Java variables, primitive/reference types, and basic method declarations
Beyond Getters and Setters: True Encapsulation
Many tutorials equate encapsulation with blindly generating private fields paired with public getters and setters for every attribute. In real engineering codebases, exposing arbitrary setters breaks invariants because any caller can overwrite balances, transition statuses illegally, or mutate internal lists behind the object’s back.
True encapsulation means hiding internal representation while exposing meaningful domain operations (deposit, reserveSeat) that validate state transitions atomically.
Immutable DTOs Since Java 17
For pure value carriers — coordinates, invoice snapshots, API DTOs — Java 16/17 record classes automatically generate final fields, canonical constructors, equals, hashCode, and toString in a fraction of traditional boilerplate while allowing compact constructor validation.
Continue this pathway with Java Collections Framework Deep Dive or reinforce OOP fundamentals via Spoken AI Technical Interviews and the Java Backend Career Program.
Practical Programming Examples
Domain Encapsulation + Validated Java 17 Record Value Object
Protect cohort capacity invariants in a domain class while representing fee breakdowns with a compact-validated Java record.
record FeeQuote(long baseInr, int gstPercent) {
FeeQuote {
if (baseInr <= 0) throw new IllegalArgumentException("Base fee must be positive");
if (gstPercent < 0) throw new IllegalArgumentException("GST cannot be negative");
}
long totalPayableInr() {
return baseInr + (baseInr * gstPercent / 100);
}
}
public class MicroCohort {
private final String code;
private final int maxCapacity;
private int enrolledCount;
public MicroCohort(String code, int maxCapacity) {
if (maxCapacity < 1 || maxCapacity > 12) {
throw new IllegalArgumentException("Micro-cohort capacity must stay between 1 and 12");
}
this.code = code;
this.maxCapacity = maxCapacity;
}
public boolean enrollStudent() {
if (enrolledCount >= maxCapacity) return false;
enrolledCount++;
return true;
}
public int seatsRemaining() { return maxCapacity - enrolledCount; }
public static void main(String[] args) {
var batch = new MicroCohort("JBCP-W1", 12);
batch.enrollStudent();
var quote = new FeeQuote(45_000L, 18);
System.out.println(batch.code + " seats left=" + batch.seatsRemaining() + ", payable=" + quote.totalPayableInr());
}
}
JBCP-W1 seats left=11, payable=53100
- Compact constructor inside `FeeQuote` validates non-positive fees immediately before fields are assigned.
- `MicroCohort` forbids external callers from directly editing `enrolledCount`, guaranteeing capacity never exceeds 12.
- Running `batch.enrollStudent()` increments internal state atomically and reports remaining seats cleanly.
Common Mistakes to Avoid
- Leaving fields `public` or adding unguarded `setBalance()` / `setStatus()` methods everywhere.
- Accepting a caller’s `ArrayList` directly without `List.copyOf(list)`, allowing callers to mutate private state externally.
Production Best Practices
- Make entity state transitions explicit domain methods rather than passive setters.
- Use Java `record` classes for immutable DTOs and read models (JDK 17+ / 21+).
Technical Interview Relevance
Expect questions comparing Encapsulation vs Abstraction and how `record` differs from classic POJOs (implicitly `final`, cannot extend classes, shallowly immutable).
Practice & Self-Check Questions
Can a Java `record` hold a mutable `List` passed to its constructor unless defensively copied?
Yes — records are shallowly immutable. Copy input collections via `List.copyOf(items)` inside the compact constructor so callers cannot mutate the backing list.