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

The entire discussion around Facebook’s disclosures of what happened in 2016 is very frustrating. No exec stopped any investigations, but there were a lot of heated discussions about what to publish and when.


In the spring and summer of 2016, as reported by the Times, activity we traced to GRU was reported to the FBI. This was the standard model of interaction companies used for nation-state attacks against likely US targeted.

In the Spring of 2017, after a deep dive into the Fake News phenomena, the security team wanted to publish an update that covered what we had learned. At this point, we didn’t have any advertising content or the big IRA cluster, but we did know about the GRU model.

This report when through dozens of edits as different equities were represented. I did not have any meetings with Sheryl on the paper, but I can’t speak to whether she was in the loop with my higher-ups.

In the end, the difficult question of attribution was settled by us pointing to the DNI report instead of saying Russia or GRU directly. In my pre-briefs with members of Congress, I made it clear that we believed this action was GRU.