This is called data or information hiding .
Basically, you donβt want the user (read: another programmer or himself) to break into the interior of his class, because it is very difficult to change.
On the other hand, the pure separation between interface and implementation (theoretically) makes it easy to change something internally without affecting users of your class.
For example, suppose I have a Button control with a public String text field. Now everyone is starting to use my Button , but I understand that every time the text is changed, the button must be repainted on the screen. I was unlucky because my object cannot determine when text is assigned. If I made it private and provided setText() instead, I could just add a redraw call to this setter method.
As another example, suppose I have some class that opens a file in its constructor and assigns it a public FileStream file . The constructor throws an exception if the file cannot be opened. Therefore, other methods in the class may assume that this field is always true. However, if someone walks in my class and sets file to null , all methods in my class will suddenly crash.
Thomas
source share