Encapsulation bundling data and method together into a single unit. Encapsulation restricts direct access to prevent accidental modification of data.
Key Components of Encapsulation:
1. Data Hiding: Encapsulation hide data from others classes by defining the fields and method private.
2. Getter and Setter: Getter and setter used for access and update the value of private variable.
Example:
class Person{
private String person_name; // private fields
// getter method getPerson_name to get or access the person_name
public String getPerson_name() {
return person_name;
}
// setter method setPerson_name to modify the person_name
public void setPerson_name(String person_name) {
this.person_name = person_name;
}
}