1. What is Encapsulation?
Encapsulation is a mechanism of wrapping data (variables) and methods (functions) together into a single unit, typically a class, and restricting direct access to some of the object’s components. This is done to protect the internal state of the object and ensure controlled access.
Think of it as a capsule: you can see some parts, but the inner workings are hidden and safe.
2. Key Features of Encapsulation
- Data Hiding – Internal object details are hidden from outside classes.
- Controlled Access – Access to fields is controlled via getter and setter methods.
- Flexibility & Maintainability – Internal implementation can be changed without affecting external code.
3. How to Achieve Encapsulation in Java
Encapsulation is achieved by:
- Declaring class variables as
private
. - Providing public getter and setter methods to access and update the variables.
4. Example of Encapsulation
class Person {
// Private variables
private String name;
private int age;
// Getter method for name
public String getName() {
return name;
}
// Setter method for name
public void setName(String name) {
this.name = name;
}
// Getter method for age
public int getAge() {
return age;
}
// Setter method for age with validation
public void setAge(int age) {
if(age > 0) { // only allow positive age
this.age = age;
} else {
System.out.println("Age must be positive.");
}
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person();
// Set values using setter methods
p.setName("Alice");
p.setAge(25);
// Get values using getter methods
System.out.println("Name: " + p.getName());
System.out.println("Age: " + p.getAge());
}
}
✅ Output:
Name: Alice
Age: 25
Notice how the internal variables
name
andage
are private and cannot be accessed directly from outside the class. Access is only through controlled getter/setter methods.
5. Benefits of Encapsulation
- Control over data – You can validate or restrict changes to fields.
- Increased security – Prevents unauthorized access.
- Ease of maintenance – Internal implementation can change without affecting other classes.
- Improves modularity – Keeps code organized and easier to understand.
6. Quick Summary Table
Feature | Description |
---|---|
Access Modifier | private for fields, public for getters/setters |
Purpose | Protect object state and provide controlled access |
Getter Method | Returns the value of private variables |
Setter Method | Sets the value of private variables (can validate) |