Search code examples
javaprivateencapsulationpublic

why we are declaring variables as private in java


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


Solution

  • 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.