Java: Why do we use getter and setter methods?
a thread...
In Java classes, we normally create the getter and setter methods to read and update class level fields respectively.
Let's find out why do we following this practice.
Consider a class "Account", having fields like accountName and accountBalance - to show the name and balance of the account.
As a common practice, both the variables are private and define the public getter and setter method to read and write their values.
Eg:
Using the above example, let's see different use-cases where having getter and setter methods can be game-changing.
1. Validation:
The public getter and setter method act as a single door to access the private fields.
Before updating the value we can run any validation in the setter method and accordingly allow field modification.
Eg: