Encapsulation in Java — Explained with Example
Encapsulation is one of the four main pillars of Object-Oriented Programming (OOPs) in Java.
It simply means wrapping up data (variables) and code (methods) together into a single unit to enhance program security and maintainability.
Think of Encapsulation like a Capsule (Tablet) — a capsule hides the medicine inside it, and you can only consume it as a whole. Similarly, encapsulation hides the internal details of a class and only exposes controlled access.
Formula of Encapsulation
Encapsulation = Data Hiding + Abstraction
Advantages of Encapsulation in Java
Improves Security — By making variables private, direct access is restricted.
Ensures Data Integrity — Values are updated only through controlled methods.
Enhances Maintainability — Large projects become easier to manage.
Increases Flexibility — Behavior of variables can be changed without affecting external code.
Better for Testing — Encapsulated classes are easier to test and debug.
IDE Support — Modern IDEs provide built-in shortcuts to generate Getter & Setter methods automatically.
Key Points about Encapsulation
To make a fully encapsulated class, declare all variables as private.
Use Getter and Setter methods to access or modify private variables.
Getter → used to read values.
Setter → used to write values.
We can also add custom logic inside setter methods for validation.
Get Quipoin’s stories in your inbox
Join Medium for free to get updates from this writer.
In some cases, getters and setters can be skipped, but using them provides better control.
Example of Encapsulation in Java
package quipoHouse;
// Main Class
class EncapsulationEx {
public static void main(String[] args) {
User obj = new User(); // Creating object of User class
obj.setName("QUIPO"); // Setting the value
String userName = obj.getName(); // Getting the value
System.out.println(userName); // Printing the value
}
}package quipoHouse;
// Encapsulated Class
public class User {
private String name; // Private variable
// Getter Method
public String getName() {
return name;
}
// Setter Method
public void setName(String userName) {
name = userName;
}
}Output:
QUIPOReal-Life Analogy of Encapsulation
Think of ATM Machine:
You don’t access bank records directly.
You interact through methods (Insert Card → Enter PIN → Withdraw Money).
Data is hidden internally but controlled access is provided.
This is exactly how Encapsulation works in Java!
Conclusion
Encapsulation in Java ensures data hiding, abstraction, and controlled access, making your programs more secure, flexible, and maintainable.
By using private fields with getter and setter methods, developers can control how data is read or modified.
Start practicing Encapsulation in your Java projects — it’s a must-have concept for every beginner and professional developer!
Also Read:





