Encapsulation is one of the important concepts of Object-Oriented Programming (OOP).
It is the process of wrapping data (variables) and methods into a single unit called a class.
In encapsulation, class variables are usually declared as private and accessed using public getter and setter methods.
Why Encapsulation is Used:
Encapsulation helps to:
Protect data from unauthorized access
Improve security
Control data modification
Make code clean and maintainable
Program:
class Student {
// private variables
private int id;
private String name;
// setter methods
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
// getter methods
public int getId() {
return id;
}
public String getName() {
return name;
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
// setting values using setter methods
s1.setId(101);
s1.setName("Sarumathi");
// getting values using getter methods
System.out.println("Student ID : " + s1.getId());
System.out.println("Student Name : " + s1.getName());
}
}
Output:

Top comments (0)