Java Encapsulation - Complete Guide
Introduction to Encapsulation
Encapsulation is one of the four fundamental OOP concepts. It refers to the bundling of data (variables) and methods that operate on that data into a single unit, called a class, while restricting direct access to some of the object's components.
Encapsulation is often achieved by declaring variables as private and providing public getter and setter methods to access and modify them. This approach is also known as data hiding.
Benefits of Encapsulation
- ✅ Increased security of data through data hiding
- ✅ Better control over class attributes and methods
- ✅ Flexible code: can change one part without affecting others
- ✅ Ability to add validation logic in setter methods
- ✅ Improved maintainability and modularity
Implementation Example
Example
public class Person {
// Private fields (encapsulated data)
private String name;
private int age;
// Public getter for name
public String getName() {
return name;
}
// Public setter for name with validation
public void setName(String name) {
if (name != null && !name.trim().isEmpty()) {
this.name = name;
} else {
System.out.println("Invalid name!");
}
}
// Public getter for age
public int getAge() {
return age;
}
// Public setter for age with validation
public void setAge(int age) {
if (age >= 0 && age <= 120) {
this.age = age;
} else {
System.out.println("Invalid age! Must be between 0 and 120.");
}
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
// Using setter methods to set values
person.setName("John Doe");
person.setAge(25);
// Using getter methods to access values
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
// Testing validation
person.setAge(150); // This will show error message
person.setName(""); // This will show error message
}
}
Output
Name: John Doe Age: 25 Invalid age! Must be between 0 and 120. Invalid name!