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.

private var variable : Int = 10

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.

Setter visibility must be the same or less permissive than property visibility.

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.

public var variable : Int = 10

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

public var variable : Int = 10
private set

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

Getter visibility must be the same as 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.