3

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())?

Community
  • 1
  • 1
wrongusername
  • 18,564
  • 40
  • 130
  • 214
  • Possible duplicate: http://stackoverflow.com/questions/2903385/property-and-encapsulation – Paolo Jun 14 '10 at 08:15
  • Just so you know, I implemented getters and setters in my program at first just as simple (and imo at the time, useless) functions to change or retrieve variables, but they turned out to be life-savers during debugging in throwing exceptions. I don't see how debugging would be quite so easy if they were public :) – wrongusername Jun 15 '10 at 20:21

5 Answers5

14

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
  • 1,245
  • 1
  • 9
  • 18
4

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
  • 37,700
  • 14
  • 97
  • 166
  • Weird thing is, that 99% of setters/getters is not meant for validation or lazy initialization...Despite of this Java is all about them... look at Pojo beans ... It's true that with IDE help they don't bother developer at all, but still ... It is irrelevant to Reflection ... Only thing that relates to it is Proxying, which requires setters/getters – lisak Jun 17 '11 at 21:44
4

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");
}
Pieter Germishuys
  • 4,828
  • 1
  • 26
  • 34
3

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
  • 66,855
  • 13
  • 106
  • 140
2

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

Matteo Riva
  • 24,728
  • 12
  • 72
  • 104