This is an example of a source code when we are using the set and get methods:
public class Dog {
private String dogName;
private int dogAge;
public Dog(String dogName, int dogAge) {
this.dogName = dogName;
this.dogAge = dogAge;
}
public String getDogName() {
return dogName;
}
public void setDogName(String dogName) {
this.dogName = dogName;
}
public int getDogAge() {
return dogAge;
}
public void setDogAge(int dogAge) {
this.dogAge = dogAge;
}
@Override
public String toString() {
return "Dog{" + "dogName=" + dogName + ", dogAge=" + dogAge + '}';
}
}
If you don't see the point of encapsulation, allow me to demonstrate with a "real life" example (which .
private boolean amIDrunk = true;
public boolean getAmIDrunk(Object asker){
if (asker instanceof PoliceOfficer){
return false;
} else if (asker instanceof DrinkingBuddy ){
return true;
}
return amIDrunk;
}
public void setAmIDrunk(boolean setter){
if (hadLessThen10Beers()) {
this.amIDrunk = false;
return;
}
this.amIDrunk = setter;
}
Sure, this is a 'nitwit' example, but it's just to show that sometimes, just because you call a setter, there might be a reason not to set that value, and sometimes, when a getter is called, there might be a reason, you don't want to return the actual value.
Anyway, to continue in this example: having amIDrunk as a private variable, makes sure someone else doesn't declare you as 'drunk' by setting amIDrunk to true, without the implementation of your own set method to agree with it.