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:
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:
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.