Encapsulation in Java is a fundamental object-oriented programming concept that restricts direct access to an object’s data and methods.
It involves bundling the data (fields) and methods that operate on the data into a single unit, typically a class. This concept enhances data security and reduces complexity.
Key Features:
1. Data Hiding: Internal state is hidden from the outside world using access modifiers (e.g., private), allowing controlled access through public methods (getters and setters).
2. Modularity: Changes in one part of the code do not affect other parts, promoting code maintainability and flexibility.
Example:
public class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
In this example, the name field is private, and access is provided via public getter and setter methods. Encapsulation ensures controlled and secure access to the object’s data.