I am learning java. Now, it is always a practice in oop to make the fields in a class private and provide get and set methods as per the requirements to access or modify the variables. Now my question is that if you have a set method for a field that is declared private, the user can still change the value of the field even if it is invisible. So, why not make the field public instead of providing a set method?
Share
Variables are best kept private (although you can keep it public). Not all variables need get and set (accessors and mutators) functions. It depends on use case. For example if I am holding the count of some sort, which is internal to the class, I would not provide a set(..) method to it. If your get(..) and set(..) methods do nothing more than returning and assigning, I would suggest you follow your company’s coding guidelines. And if you have the option go for getters and setters.
A very simple/trivial example here:
HTH ..