Encapsulation in Java
Problem
Encapsulation means hiding a class's fields behind private access and only exposing controlled ways to read or change them, so invalid state can be rejected before it's ever stored.
Define an Employee class with a private salary field that rejects a negative value when set.
Java Program
class Employee {
private double salary;
void setSalary(double salary) {
if (salary < 0) { // reject invalid state before it's ever stored
System.out.println("Rejected: salary cannot be negative");
return;
}
this.salary = salary;
}
double getSalary() {
return salary;
}
}
public class EncapsulationDemo {
public static void main(String[] args) {
Employee emp = new Employee();
emp.setSalary(-500.0);
emp.setSalary(50000.0);
System.out.println("Salary: " + emp.getSalary());
}
}Output
Core Logic
Making salary private and only reachable through setSalary() means every attempt to change it passes through a validation check first, something a public field could never enforce.
- 1
private double salary;can't be read or written directly from outsideEmployee—emp.salary = -500.0;wouldn't even compile. - 2
setSalary(double salary)checkssalary < 0before storing anything, rejecting the invalid value instead of accepting it. - 3The first call,
setSalary(-500.0), is rejected andsalarykeeps its default value of0.0. - 4The second call,
setSalary(50000.0), passes the check and actually updates the field.
getSalary() returns 50000.0 — the negative attempt never touched the field at all.Key Point: If salary had been a public field instead, nothing would have stopped code elsewhere from setting it directly to a negative value — encapsulation is what makes the validation actually enforceable. This is the why behind hiding fields; Getter and Setter covers the specific accessor/mutator naming convention on its own.