Encapsulation in Java is the process of wrapping data (variables) and the code that acts on that data (methods) together as a single unit, typically a class.
Encapsulation in Java is achieved using:
- Private data members,
- Public getter and setter methods.
Benefits:
Data Control: You can make a class read-only (by providing only getters) or write-only (by providing only setters).
Validation: Setters allow you to add logic to validate data before it is saved (e.g., ensuring an age is not negative).
Security: It protects sensitive internal states from unauthorized modification.
Maintainability: You can change the internal implementation of a class without breaking the code that uses it.
Example : class Programmer {
private String name;
public String getName() { return name; }
public void setName(String name) {
this.name = name;
}
}
public class Geeks {
public static void main(String[] args){
Programmer p = new Programmer();
p.setName("Geek");
System.out.println("Name=> " + p.getName());
}
}
Output: Name=> Geek

Top comments (0)