Getters and setters coming from data hiding. Data Hiding means We are hiding data from outsiders or outside person/thing cannot access our data.This is a useful feature in OOP.
As a example:
If you create a public variable, you can access that variable and change value in anywhere(any class). But if you create as private that variable cannot see/access in any class except declared class.
public
andprivate
are access modifiers.
So how can we access that variable outside:
This is the place getters and setters coming from. You can declare variable as private then you can implement getter and setter for that variable.
Example(Java):
private String name;public String getName(){ return this.name;}public void setName(String name){ this.name= name;}
Advantage:
When anyone want to access or change/set value to balance
variable, he/she must have permision.
//assume we have person1 object//to give permission to check balanceperson1.getName()//to give permission to set balanceperson1.setName()
You can set value in constructor also but when later on when you wantto update/change value, you have to implement setter method.