I have been reading about getters and setters and I have a question. Are getters and setters supposed to be used when accessing the variables in the class that declared the variables? It seems like there is no need for getters and setters here because it doesnt matter that the variable is private, the class that declared it will always have access to it….?
Or are getters and setters only supposed to be used when external classes want to access these variables?
While the language doesn’t require you to do so, it is good practice to use getters and setters when accessing private fields that are exposed through getters and setters. In some cases I would even go so far as to say that it makes sense to use them even for internal properties that are not directly exposed (yet).
The reason it is good practice to do so is because it isolates the code that reads and modifies the private fields to a single set of methods. That way you can later provide extra validation, or even change the way the property is stored internally without having to change too many places.
An example of a change might be a class that exposes, through getter (accessor) / setter (mutator) methods, a certain property that is initially stored as a private field in that class. Later you realise that you need to use a different storage repository for that property – maybe read it from a file, or from a database etc. At that point if you’ve only used the methods to access and modify the property you can simply change the code of the accessor and mutator methods to implement the change.
Another example would be instances when the class is extended. It provides better encapsulation.
And even for testing it makes sense to abstract access to the private “storage repository” for a logical property.
Note: I’m referring to the concept of the private member you’re exposing as a property of the class even though Java doesn’t necessarily refer to them as such.
Finally, I can’t stress enough that my recommendation to use methods instead of directly accessing the private member is just that: a recommendation. It’s considered by many to be good practice and as such I recommend you follow, but by all means feel free to not follow if you have a good reason not too!