Let's find out why do we following this practice.
Java: Why do we use getter and setter methods?
a thread...
Let's find out why do we following this practice.
As a common practice, both the variables are private and define the public getter and setter method to read and write their values.
Eg:

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:

Similar to Validation, we can also put any security-related code to secure our data inside the getter and setter.
For eg. Check if a user has access to the field based on our complex security logic and then allow the user to either read or update the value.
To allow only write permission, we can keep setter methods.
Similarly, to allow only read permission to fields, we can remove the setter method and only keep the getter method as shown below:

To create an immutable class, we can remove the setter and put-getter methods.
In getter methods, we can return a new copy instead of returning the original object to protect it from getting modified.

In the above scenarios, we've only achieved encapsulations at diff levels & that's the main reason for using getter/setter in java.
To see the above examples in more detail and run them you can access below git repo:
https://t.co/vHZsSmtJqS