views:

116

answers:

5

Possible Duplicates:
Public Data members vs Getters, Setters
Purpose of private members in a class

What is the use of getters and setters when you can just make your variables public and avoid the hassle of such lines as A.setVariableX(A.getVariableY())?

+5  A: 

To hide implementation details. If you choose to make your properties public instead, then later decide to change the way they work, you have to change all of the associated code.

With getters and setters, you can often change the internal implementation details without changing the visible API (and thus avoid having to change any of the code that uses the API of the class in question).

AllenJB
A: 

It's part of the encapsulation principle. You use setters and getters as an interface to interact with your object so that you can - for example - later add any functionality (like validating input data) without touching the code that uses the class(es).

kemp
+3  A: 

Getters and setters can do validation, and lazy instantiation, whereas public members cannot.

As an aside, this isn't language agnostic, as most of the languages that implement properties abstract away the implementation so they look like public members in code.

Rowland Shaw
+3  A: 

Because sometimes there are some constraints as to what your variable might be and having to check that when you set it make sense.

for instance, if your Age is not allowed to be -1, you would check that in your setter.

if(value >= 0)
{
   _age = value;
}
else
{
  throw new InvalidAgeException("Age may not be less than 0");
}
PieterG
+2  A: 

Setters and getters apply to properties, whatever "properties" are in your code.

For instance, you can have an angle variable, which stores an angle value expressed in radians. you can then define setters and getters for this variable, with any angle unit that you think relevant.

mouviciel