Understanding Encapsulation in Java
Encapsulation is one of the four pillars of OOPs. It means wrapping data (fields) and the methods that operate on that data into a single unit — a class — while restricting direct access to the internal state.
How to Achieve Encapsulation
- Declare class fields as
private - Provide public getter and setter methods to read and update the fields
- Add validation logic inside setters to control what values are allowed
Example
class Employee {
private String name;
private double salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
if (salary > 0) {
this.salary = salary;
}
}
}
Benefits of Encapsulation
- Protects object state from unauthorized or invalid modification
- Hides implementation details, exposing only what's necessary through a clean interface
- Makes code easier to maintain, since internal changes don't affect external code
- Improves security by controlling how fields are accessed and updated
A fully encapsulated class in Java is often called a POJO (Plain Old Java Object) when it consists mainly of private fields with public getters and setters.
Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.