I don't understand Access Modifiers in OOP. Why do we make for example in Java instance variables private and then use public getter and setter methods to access them? I mean what's the reasoning/logic behind this?
You still get to the instance variable but why use setter and getter methods when you can just make your variables public?
please excuse my ignorance as I am simply trying to understand why?
Thank you in advance. ;-)
This is called data or information hiding.
Basically, you don't want a user (read: other programmer, or yourself) poking in the internals of your class, because that makes it very hard to change things.
On the other hand, a clean separation between interface and implementation (theoretically) makes it easy to change something internally, without affecting any users of your class.
For example, suppose I have a Button
control with a public String text
field. Now everybody starts using my Button
, but I realize that the button should actually be repainted on the screen whenever the text changes. I'm out of luck, because my object can't detect when text
is assigned. Had I made it private
and provided a setText()
instead, I could just have added a repaint call to that setter method.
As another example, suppose I have some class that opens a file in its constructor and assigns it to a public FileStream file
. The constructor throws an exception if the file could not be opened. The other methods in the class can therefore assume that this field is always valid. However, if somebody goes poking around in my class and sets file
to null
, all methods in my class will suddenly start crashing.
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