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

Moderna CEO Stephane Bancel was previously CEO of bioMerieux in France from 07-10.

Alain Merieux, who owns bioMerieux, was instrumental in the creation of the Wuhan Institute of Virology P4 Lab.

The same people who helped create the virus, also helped to create the vaccines...


Moderna partnered with French Pasteur Institute in 2015 to develop mRNA vaccine technology.

Pasteur Institute partnered with the Wuhan P4 Laboratory in 2017 along with the Merieux Foundation to study emerging viruses...
https://t.co/yFsHwrNYaK
https://t.co/9M5lydBKhM


Nobel prize winning scientist Luc Montagnier asserts that Sars-Cov-2 is man-made and originated from the Wuhan Institute of Virology.

Montagnier did extensive work with the Pasteur Institute in France which was partnered with the Wuhan P4.

Merieux Foundation & the Chinese government have worked together since 1965, and partnered to study emerging pathogens in Africa in 2015.

Their research included "PATHOGENS CARRIED BY BATS" that provoke respiratory diseases.

🚨🚨🚨
https://t.co/gVwpT0ssqI