I saw a code where getters and setters methods are declared private. I am trying to figure out the logic behind it, and I am really having hard time to understand why would you declare them as private? That's exactly opposite of what we are trying to achieve through getters and setters.
Usually you want setters/getters to be public, because that's what they are for: giving access to data, you don't want to give others direct access to because you don't want them to mess with your implementation dependent details - that's what encapsulation is about.
The answer is it can be accessed only from within the class in which it is declared. Any private member of the class can be accessed only from within the class in which it is declared. How do you interact with a private variable from another class in Java?
Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.
In general, they should be public. If they are private they can only be called from within your class and, since you already have access to the private variables within your class, are redundant. The point of them is to allow access to these variables to other, outside, objects.
I can think of several reasons:
If a different programmer sees your code and wants access to a variable, but there are no setters and getters, he might think you just forgot about them, and add them themselves. However, if you declare them as private
, it's a statement of intent, saying I don't want these variables to be changed or accessed from the outside.
Say you don't want public
accessors. But maybe you want a count of how many times a private variable is changed. It's easier to use a setter rather than incrementing the count every time you access that variable.
Again, you don't want public
access, but during debugging, you might want to put a breakpoint in every place a private
member is changed. So instead of setting breakpoints everywhere in the class, you just set one in the accessor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With