I have a confusion in how do getter and setter provide encapsulation. I mean what is the difference between assigning value to a variable directly and assigning them through getter and setter. Also lets say we have two class A & B. While using getter and setter to set values from class B we have to make an object of class A in class B, so how are the variables encapsulated when we already know in which class they are defined.
With setters we can apply extra validation on the specified value which won't be possible when you assign the value directly to the property. A example could be to check whether the value is not null for example:
public void setVariable(Object value) {
if (value == null) {
throw new IllegalArgumentException();
} else {
...
}
}
Other possibilities you get with setters is that you can apply extra computations. If you would for example have a BankAccount instance and you change the interest the setter could initiate recalculation of the interest that has to be paid to the user.
A possibility you get by applying a getter is that you can return default value in case the value is not set yet.
Another appliance of the getter and setters is restricting the access to the variable. We could for example make the getter public while the setter is protected. This means that everybody can read the property but only classes that extend the other class, or are in the same package can set the value.
Regarding your second question. I don't fully understand the question. Could you elaborate a bit more on that one.