What is Encapsulation?
Encapsulation is one of the fundamental principles of Object-Oriented Programming (OOP). It refers to wrapping data (fields) and methods (functions) that operate on the data into a single unit (class) — and restricting direct access to that data.
Key Points:
- Data is hidden from outside classes.
- Access to data is provided through getters and setters.
- Improves security, modularity, and maintainability.
How to Achieve Encapsulation in Java:
- Make fields
private
. - Provide public getter and setter methods to access and update the values.
Example: Encapsulation in Java
class Employee {
// Step 1: private fields
private String name;
private int salary;
// Step 2: public getter and setter methods
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
public int getSalary() {
return salary;
}
public void setSalary(int newSalary) {
if(newSalary > 0) {
salary = newSalary;
} else {
System.out.println("Salary must be positive!");
}
}
}
public class Main {
public static void main(String[] args) {
Employee emp = new Employee();
emp.setName("John Doe");
emp.setSalary(50000);
System.out.println("Name: " + emp.getName());
System.out.println("Salary: ₹" + emp.getSalary());
}
}
Output:
Name: John Doe
Salary: ₹50000
Why Use Encapsulation?
Benefit | Description |
---|---|
Data hiding | Prevents unauthorized access to data |
Controlled access | Get/set data using methods with logic |
Improved maintenance | Easy to change one part of code without affecting others |
Reusable code | Well-structured, self-contained classes |
Real-Life Analogy:
Think of ATM machines:
- You don’t access the internal logic.
- You interact through buttons (methods).
- Your PIN and balance (data) are encapsulated and secure.
Summary
Keyword | Meaning |
---|---|
private |
Access modifier to hide data |
getter |
Method to return the value of a field |
setter |
Method to set/update the field value |
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.