just to clarify it is a good practice to set a classes fields as private and then set public set and get methods to change the values, and obtain them (print them etc)? JUst so I know, I read in my book it can be a bad practice to declare my fields as public a lot...
4 Answers
The reason why you'd have getters and setters is so that you can potentially introduce logic into them in the future.
If your code already uses getters and setters, instead of just accessing the fields straight, than putting logic into your getters/setters won't break other programs that use your code.
for instance, you can change
private i
public set_i(int x)
{
i = x;
}
into
private i
public set_i(int x)
{
if(x < 0)
i = 0;
else
i = x;
}

- 30,851
- 12
- 72
- 100
In short, yes. This insulates the consumer from changes to the implementation later. It feels like a drag at first but it's only a small amount of boilerplate work. And it keeps the get/set paradigm consistent across methods that actually do something non-trivial.

- 7,057
- 3
- 23
- 33
If you're not gonna implement or add to the current Set or Get normal method, just don't use them and use the public instead, but for other uses like custom implement another behavior or functionality use them.

- 11,940
- 3
- 28
- 36
If you're asking why it's good to use setters and getters, which I assume you are, it's good for a couple of reasons:
- You can store logic in them which can be used by multiple classes.
- The variable can be read only or write only (improves safety of code).

- 1,816
- 1
- 12
- 19
-
And it can make debugging easier as you can easily check from where a variable is being set. – matt helliwell Oct 07 '13 at 20:34