All topics
library
beginner

Encapsulation in Java

Hide internal state behind access modifiers and expose behavior through public methods.

Encapsulation is the OOP mechanism of bundling data (fields) with the methods that operate on that data and restricting direct access to the fields from outside the class. In Java, encapsulation is implemented through access modifiers — making fields private and providing public getter and setter methods.

A bank account: you can't reach into the vault (private balance). You use the teller window (public methods) which enforces rules like 'no overdraft.'

Key Concepts

1
The core benefit is control: by routing all access through methods, you can add validation, logging, computed values, or change the internal representation without breaking callers. A setAge(int age) method can reject negative values; a raw public field cannot. This is sometimes called 'data hiding,' though the more precise term is 'information hiding' — you're hiding the implementation detail, not necessarily the existence of the data.
setAge(int age)
2
Encapsulation also enables the uniform access principle: callers don't know (or care) whether getFullName() reads a stored field or concatenates first and last name on the fly. This decouples the API from the storage, which is critical in large codebases where changing a field type should not cascade into hundreds of files.
getFullName()
3
A common interview trap: confusing encapsulation with just 'making fields private.' True encapsulation means the API reflects behavior, not storage. A class with getters/setters for every field is barely encapsulated.