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:
2. Security

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.
3. ReadOnly or WriteOnly Permission

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:
4. Immutability:

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.
Conclusion:

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

More from Vikas Rajput

You May Also Like

First update to https://t.co/lDdqjtKTZL since the challenge ended – Medium links!! Go add your Medium profile now 👀📝 (thanks @diannamallen for the suggestion 😁)


Just added Telegram links to
https://t.co/lDdqjtKTZL too! Now you can provide a nice easy way for people to message you :)


Less than 1 hour since I started adding stuff to https://t.co/lDdqjtKTZL again, and profile pages are now responsive!!! 🥳 Check it out -> https://t.co/fVkEL4fu0L


Accounts page is now also responsive!! 📱✨


💪 I managed to make the whole site responsive in about an hour. On my roadmap I had it down as 4-5 hours!!! 🤘🤠🤘