Aniket Bhoite By setting a getter private and setter public, we will break the encapsulation rule.

I’ll explain you with an example.

Let’s say we have one integer variable.
We’ll discuss all the possibilities of access modifiers/visibilities of getter and setter for the property as private and public.

Let’s take the case of the private variable first.

By default, the getter and setter both will have private visibility too. If you try to increase the visibility of setter of the variable, you will see the below error.

which clearly indicates that we can not increase the visibility of property setter.
There is no point in increasing the visibility of getter as we can use a public property instead and also it is not possible.

Now let’s take the case of public property.

In this case, the default visibility of both getter and setter is public.
Now we can reduce the visibility of setter to private.

And it’ll work fine but we can not reduce the getter visibility as it must be same as the property visibility.

Two things to keep in mind
1. The getter visibility will be defined by the visibility of property.
2. The setter visibility can only be reduced or restricted to a less permissive visibility of the property.

Encapsulation says

  • You cannot read and write the value of a variable (from outside the class) if it is private.
  • You can read the value of a variable but cannot write (from outside the class) if the variable is public but the setter is private.
  • You can read and write the value of a variable (from outside the class) if the variable is public.

There is no such case where you can write the variable value from outside the class but you cannot read it.




Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Suneet Agrawal

Suneet Agrawal

More from Medium

Rewrite Your Narrative — You Save Yourself in this One

DO network’s technical characteristics of the interpretation

Are Canada’s immigration laws good?