Encapsulation is one of the four fundamental Object-Oriented Programming (OOP) principles (along with inheritance, polymorphism, and abstraction). It refers to the concept of bundling the data (fields) and methods (functions) that operate on the data into a single unit, known as a class. Additionally, encapsulation also involves restricting direct access to some of the object’s components, which is achieved by using access modifiers (such as private, protected, public).
Why use Encapsulation?
There are three points to describe it.
1. Protect the integrity of the data by preventing unauthorized access or modification.
2. Provide a controlled way to access or modify data via getter and setter methods.
3. Hide implementation details and expose only necessary functionality.
Benefits of Encapsulation
Control Over Data: You can control how data is accessed or modified by providing validation in setter methods.
Code Maintenance: You can change the internal implementation of a class without affecting its external usage. The users of the class interact only with the public methods.
Security: Encapsulation helps protect data from being accessed directly or modified in unintended ways, reducing the risk of errors or unauthorized access.
Example:
// Class Employee
class Employee {
// Private fields
private String name;
private int age;
// Public getter method for 'name'
public String getName() {
return name;
}
// Public setter method for 'name'
public void setName(String name) {
this.name = name;
}
// Public getter method for 'age'
public int getAge() {
return age;
}
// Public setter method for 'age'
public void setAge(int age) {
if (age > 0) { // Adding validation in setter
this.age = age;
} else {
System.out.println("Age should not be negative.");
}
}
}
// Main class to demonstrate Encapsulation
public class Main {
public static void main(String[] args) {
// Creating an object of Employee class
Employee employee = new Employee();
// Using setter methods to set values
employee.setName("John");
employee.setAge(30);
// Using getter methods to access values
System.out.println("Name: " + employee.getName());
System.out.println("Age: " + employee.getAge());
// Trying to set an invalid age
employee.setAge(-25); // Will print: "Age should not be negative."
}
}
Explanation:
1. In the above code, name and age are private fields, meaning they cannot be accessed directly from outside the Employee class.
2. The getter and setter methods (getName(), setName(), getAge(), setAge()) allow controlled access to these private fields.
3. The setter for age includes a validation to ensure the age is positive, which is an example of enforcing business logic during data modification.