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.