Getters and setters are used to provide controlled access to class variables while maintaining encapsulation. Although fields can be made public, doing so exposes the internal state of an object and reduces control over how data is accessed or modified.
Key Points: • Getters and setters help implement encapsulation by hiding internal data. • They allow validation before updating a variable's value. • Business rules can be enforced without changing external code. • Internal implementation can be modified later without affecting other classes. • They improve maintainability, security, and flexibility of the application.
Example: Consider an Employee class where age should never be negative. If the age field is public, any class can assign an invalid value. Using a setter allows validation before updating the field.
Code Example:
public class Employee {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
if (age >= 0) {
this.age = age;
} else {
System.out.println("Invalid Age");
}
}
}
public class Demo {
public static void main(String[] args) {
Employee emp = new Employee();
emp.setAge(25);
System.out.println(emp.getAge());
}
}Without Getters and Setters:
public class Employee {
public int age;
}
Employee emp = new Employee();
emp.age = -100; // Invalid value can be assigned directlyBenefits of Getters and Setters:
• Data validation • Better encapsulation • Improved security • Easier maintenance • Flexibility to change implementation later
Interview Tip: A concise interview answer is:
"We use getters and setters instead of public fields to maintain encapsulation and control access to data. They allow validation, enforce business rules, improve security, and provide flexibility to change the internal implementation without affecting other parts of the application."