The Purpose of Getters and Setters
What you'll learn: Why we use special methods to access private fields instead of making those fields public.
The Problem with Direct Field Access
Imagine making all your class fields public. Anyone could reach in and change your object's internal state directly, bypassing any validation or logic you intended. This breaks encapsulation — the principle that a class should control its own data.
When fields are public, you lose control:
- No way to validate values before they're set
- No way to track when values change
- Internal representation changes force all code using your class to change
- Can't make fields read-only or write-only
Enter Getters and Setters
Accessor methods (getters and setters) solve this by providing controlled access to private fields:
- Getters (
getFieldName()) let others read a field's value - Setters (
setFieldName(value)) let others write a field's value with validation
Think of it like a bank vault: you don't hand customers the combination (direct field access). Instead, you provide a teller window (methods) where transactions are monitored and validated.
Why This Matters
With getters and setters, you maintain control:
- Validate input before accepting changes
- Add logging or notifications when values change
- Change internal storage without breaking external code
- Make some fields read-only (getter without setter)
- Compute values on-the-fly instead of storing them
By keeping fields private and exposing them only through public methods, you protect your object's internal state while still providing necessary access.
Key Takeaway: Getters and setters enforce encapsulation by giving you controlled access points to private fields, allowing validation, flexibility, and protection of internal state that direct public field access cannot provide.