Purpose:
-
Getters (
getXxx()
) → Read private fields. -
Setters (
setXxx()
) → Modify private fields (with optional validation).
Example:
class Student {
private String name;
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String name) {
if (name != null) {
this.name = name;
}
}
}
Why Use Them?
✔ Encapsulation (hide internal data)
✔ Control access (add validation/logic)
✔ Flexibility (change internals later)
Lombok Shortcut:
@Getter @Setter
class Employee {
private int id;
}
(Auto-generates getId()
and setId()
)
Key Rule:
→ Always use private fields + public getters/setters for secure OOP design. 🛡️