Getters, Setters
Because fields are private
for safety, you still need a controlled way to read and write their values from outside.
This is where getters and setters come in:
A getter lets you read a fieldโs value.
A setter lets you change a fieldโs value โ but only with your validation rules.
Together, they act like gatekeepers.
They give you full control over:
What is visible,
What is changeable,
And how.
Letโs see a simple Person
class that uses getters and setters.
Key points:
Fields are private.
getName()
and getAge()
return the current values.
setName()
and setAge()
update values โ setAge()
checks for valid input.
This pattern keeps the classโs internal data safe and prevents illegal values.
Below is a mini program that shows how to use getters and setters in practice.
When you run it:
The Person
object p
has private fields.
You set them safely through setters.
You read them safely through getters.
Direct modification is impossible from outside.