Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why we are declaring variables as private in java [duplicate]

Normally in java bean classes we are declaring variables as private. Anyhow we are declaring setter and getter methods as public. Then we are able to get and set the value of property. So what is the use of declaring variable as private here? What happen if I declare as public?

Thanks in advance..

like image 203
samba Avatar asked May 07 '26 01:05

samba


1 Answers

That is the purpose of encapsualtion.

Consider having an age property and you want to have some control over it. If you expose your field simply as public, you can just access it externally and do whatever you want with it. Then, checking that the age is valid can be a little bit of a hassle.

That being said, with a setter method, you could, for instance, have a verification mechanism in place. This provides you with control over how and when is your variable accessed and changed.

The same applies for getter methods. Imagine you have some internal structure you do not want to expose, say, you use enumerations internally. However, you do not want to show this outside your class. So for instance, in your getter you yield the string version of whatever value you want to yield.

like image 136
npinti Avatar answered May 09 '26 14:05

npinti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!