Encapsulation in Java is one of the four fundamental Object-Oriented Programming (OOP) principles. It is the process of wrapping data (variables) and code (methods) together as a single unit to protect data and maintain control over it.
Encapsulation means restricting direct access to some of an object's components. This is achieved using access modifiers like private, protected, and public. Encapsulation ensures that data is hidden and controlled properly through getter and setter methods.
The main objectives of encapsulation are to protect object data from unauthorized access, improve code maintainability, and control how important variables are accessed or modified. By using encapsulation, you ensure the integrity and security of your data.
Encapsulation provides data hiding which ensures the security of object data. It improves flexibility and reusability of code, as internal implementation can change without affecting outside code. It also makes debugging and maintenance easier since access to variables is controlled.
Using encapsulation can increase code size because of the getter and setter methods. If not designed properly, it can make debugging more complex. Encapsulation is not effective unless proper access control is implemented for all variables.
In Java, encapsulation works by declaring class variables as private and providing public setter and getter methods. These methods allow controlled access to the variables instead of accessing them directly.
class Student {
private String name; // data hidden from outside world
// Setter method
public void setName(String name) {
this.name = name;
}
// Getter method
public String getName() {
return name;
}
}
public class TestEncapsulation {
public static void main(String[] args) {
Student s1 = new Student();
s1.setName("Bhau Automation");
System.out.println("Student Name: " + s1.getName());
}
}
Always keep variables private and use getters and setters for controlled access. Encapsulate related data and behavior within one class. Properly use access modifiers to ensure better security and maintain clean code.