good question, but the answer goes back to the need to encapsulate, that
is "hide" details concerning the implementation of a given class from
the outside world. coming from a visual basic world, you may find this
to be unnecessary, but it is intended as a measure to reduce complexity
in code.
while having these set/get pairs may seem to be an annoyance, they give
you flexibility at later time to change the standard behavious from
"return x" or "x=" to anything more complicated that is required by
future system requirements. if your class function suddenly has to find
the value of x based on the results from another class, or even
dynamically, then this complication can be resolved by writing a more
appropaite set/get function. supported code that relies on this class
then does not have to be altered....!
know what i mean...
also, in many ways encapsulation phyloposhy comes from the expression
"keep them in the dark and feed them horse manure" also known as the
Mushroom approach.
works great for management too...
- perry
Liz wrote:
It provides a door that seems to be open in your
example, but allows the code owner to close the
door by adding code to the accessor.
"Kiwi" <ki**@s05.itscom.net> wrote in message
news:dc**************************@posting.google.c om...
Hello.
I know a getter can return other thing than a field.
I know a setter can do more things than setting a field.
I know there are "setter only" cases and "getter only" cases.
I do use getters and setters when needed.
But most of getter/setter pairs I have seen are just like below;
private int x;
public int getX() { return x; }
public void setX(int x) { this.x = x; }
I cannot understand it is better than below.
public int x;
How do you think?
Thank you in advance.