buu said:
can anyone tell me or give me some link?
I'm newbie in java, and get used to work in .net, and getters/setters
confuse me a little bit.
The idea behind {g,s}etters is that it gives the person who writes the
class a chance to catch all access to a variable. Publicly exposing the
variable is often a bad thing, and is highly warned against.
An example of when {g,s}etters are useful would be in a point class:
class Point {
private double x, y;
private double r, theta;
double getX();
double getY();
double getR();
double getTheta();
double setX(double x);
double setY(double y);
double setR(double r);
double setTheta(double theta);
}
[ Method bodies not shown for conciseness ]
If the variables were made public, it would be the client's job to
ensure that the rectangular/polar coordinates were kept in sync. With
the {g,s}etters, the class can transparently maintain the two variables,
potentially even removing the r and theta variables.
In short, {g,s}etters:
1. allow the class to internally keep related variables in sync.
2. provide for pseudo-variable support.
3. allow the internal structure to be modified without affecting the
public API.
4. allow the class to keep track of accesses and perform sanity checks.
5. shift the burden of bookkeeping away from the clients.
There are some OO languages that even have get/set overloading (e.g.,
PHP, Python).