Encapsulation means hiding data.
You keep the data safe inside a class and don’t let anyone access it direct
🔹 2. We use private variables to protect data.Private means no one can access the variable directly from outside the class
🔹 3. We use public methods to access or change the data.
These methods are called getters and setters.
🔹 4. Encapsulation makes the program secure and easy to manage
public class Student {
private String name;
private int age;
// Getter method for name
public String getName() {
return name;
}
// Setter method for name
public void setName(String name) {
this.name = name;
}
// Getter method for age
public int getAge() {
return age;
}
// Setter method for age
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
}
example, ::
1)the Student class has private fields name and age.
2)Public getter and setter methods are provided to access and modify these fields.
3)The setter for age includes a basic validation check.
Getter setter differenciate
Top comments (1)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.