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.
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.
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());
}
}public class Employee {
public int age;
}
Employee emp = new Employee();
emp.age = -100; // Invalid value can be assigned directlyA 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.
Last updated: 11 November 2026
Previous question: Can you provide examples of when to use each type of access modifier?
Next question: Can a top-level class be private or protected in Java?