Encapsulation is one of the four fundamental principles of Object-Oriented Programming (OOP).
It is the
mechanism of bundling data (variables) and the methods (code) that operate on that data into a single
unit, typically a class.
Key Concepts
Data Hiding: Restricting direct access to class members to protect internal state.
Single Unit: Variables and methods are wrapped together like a "capsule".
Controlled Access: Interaction with data happens only through predefined interfaces (methods).
How to Achieve Encapsulation
To implement encapsulation in Java, follow these two steps:
1. Declare variables as private : This prevents direct access from outside the class.
2. Provide public Getter and Setter methods: These act as the bridge to view or modify the private
data.
Code Example
public class Employee {
// 1. Private variables (Data Hiding)
private String name;
private double salary;
// 2. Public Getter (Access)
public String getName() {
return name;
}
// 3. Public Setter with Validation (Control)
public void setSalary(double newSalary) {
if (newSalary > 0) {
[Link] = newSalary;
}
}
}
Benefits of Encapsulation
Security: Protects sensitive data from unauthorized or accidental modification.
Maintainability: Internal implementation can change without breaking external code.
Flexibility: You can make a class read-only (only getters) or write-only (only setters).
Data Validation: Setters allow you to check if the data being entered is valid before saving it.
Loose Coupling: Reduces dependencies between different parts of the application.
Encapsulation vs. Abstraction
Feature Encapsulation Abstraction
Focus How it is done (Implementation) What it does (Essential features)
Goal Hiding data (Data Security) Hiding complexity
Method Access modifiers (private, public) Abstract classes and Interfaces