When we have a setter method for private variable in java, what is the purpose of making the variable private?
We are having private variables to restrict the user not to access the state of an instance directly. But in sometimes, we are having corresponding setter and getter methods to access and change the state of the private variable. If so, then why do we make the variable private? We can just have public variable instead right?
The rationale is that you're hiding the implementation. When you call
setX(23);
your corresponding variable x
is hidden from client classes and can't be directly observed or modified.
Why is this good ?
x
at a later date to (say) a string
, a double
etc. and your client code doesn't have to change. x
could even disappear and calling setX()
would actually perform some different but equivalent function.x
to an invalid (e.g. negative) value.x
there will exist a corresponding getX()
/setX()
(or isX()
if it's a boolean
). By adhering to convention your class will interoperate nicely with these frameworks.Note there are arguments for not having setters but rather implementing immutable objects (so you'd set your value via the constructor alone). That makes the object thread-safe and debugging/reasoning about the object state easier.
It isn't a question of having a setter or not, it's a matter of encapsulation: member variables should almost always be private in order to hide the implementation.
Here's a good example I've recently seen: someone was asking why Java doesn't have an AtomicFloat
type and someone else pointed out that you can actually implement it using AtomicInteger
and doing bit tricks to convert back and forth between int
and float
. Now the class looked something like:
class AtomicFloat {
private AtomicInteger value;
public float get() {
// turn value into float
}
public void set(float newValue) {
// turn newValue into int
}
// CAS and whatever else
}
Now to the outside it seems I have all I need: I can use this class as an AtomicFloat
and I don't care about what's going on inside. Now imagine if the user could peek in and see that all my methods are actually doing stage magic with an AtomicInteger
. That would really mess things up!
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