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
More from Vikas Rajput
You May Also Like
1. Project 1742 (EcoHealth/DTRA)
Risks of bat-borne zoonotic diseases in Western Asia
Duration: 24/10/2018-23 /10/2019
Funding: $71,500
@dgaytandzhieva
https://t.co/680CdD8uug
2. Bat Virus Database
Access to the database is limited only to those scientists participating in our ‘Bats and Coronaviruses’ project
Our intention is to eventually open up this database to the larger scientific community
https://t.co/mPn7b9HM48
3. EcoHealth Alliance & DTRA Asking for Trouble
One Health research project focused on characterizing bat diversity, bat coronavirus diversity and the risk of bat-borne zoonotic disease emergence in the region.
https://t.co/u6aUeWBGEN
4. Phelps, Olival, Epstein, Karesh - EcoHealth/DTRA
5, Methods and Expected Outcomes
(Unexpected Outcome = New Coronavirus Pandemic)
Risks of bat-borne zoonotic diseases in Western Asia
Duration: 24/10/2018-23 /10/2019
Funding: $71,500
@dgaytandzhieva
https://t.co/680CdD8uug
2. Bat Virus Database
Access to the database is limited only to those scientists participating in our ‘Bats and Coronaviruses’ project
Our intention is to eventually open up this database to the larger scientific community
https://t.co/mPn7b9HM48
3. EcoHealth Alliance & DTRA Asking for Trouble
One Health research project focused on characterizing bat diversity, bat coronavirus diversity and the risk of bat-borne zoonotic disease emergence in the region.
https://t.co/u6aUeWBGEN
4. Phelps, Olival, Epstein, Karesh - EcoHealth/DTRA
5, Methods and Expected Outcomes
(Unexpected Outcome = New Coronavirus Pandemic)