Possible Duplicate:
Why use getters and setters?
Yes, It's a very simple thing but I am not finding a good reson for this. I know it is a good practice to make a variable private and providing getter to setter to access that variable. Still Is there any reason other than this ?
Lookup "encapsulation" and "information hiding".
Basically, a class manages data and provides operations on them/ give access to them, but the internal representation of that data should kept private to the class. Like this, a class can change its internal representation without breaking other code.
E.g. consider:
A)
public Date date;
B)
private Date date;
public Date getDate(){...}
public setDate(Date date){...}
Later you choose to use Calendar instead of Date.
In case A) you cannot change the data type without breaking code.
In case B) you can do:
private Calendar calendar;
public Date getDate(){...}
public setDate(Date date){...}
public Calendar getCalendar (){...}
public setCalendar(Calendar calendar){...}
You can provide a conversion in the get/setDate methods. Client code doesn't break.
Another reason you sometimes want to use getter and setter is the use of libraries/
frameworks which base on JavaBeans patterns.
There are many reasons. It is a way to control access(accessors) to the inner workings of your class. Sometimes for example you may want the getter to return a clone of the object or the setter to just copy values on the private object rather than pointing the handler to the new object passed to the setter. Another reason would be to do something before or after you get or set an object without exposing this functionality.
To sum it up:
- You give room for future extensions
- You close the door to uncontrolled access
Use them only if needed though.
If you leave variable public, you can't make sure the object will keep consistent state. In your setters you can for example have some checking like e.g. avoid setting negative number as age.
If you have public variable you drop for example possibility of having listeners since listeners are typically using notifications on setting the variable via setter. There is no chance to track the change when directly changing public variable.
These are some very basic examples but can be found more for sure.