I have simple but stupid question. We use access modifiers in Java to access variables in a Class. I do not understand that if we can access a private class variable outside the class using properties defined in public class, then what is difference between public and private? It is still accessible outside private class. I do not understand the concept of this public private concept.
Share
If I understand your question correctly, you are asking why someone would write this:
instead of simply:
The main reason is to hide the internal structure of
MyClassfrom client code. The benefit is that this allows you to more easily modify the internal structure ofMyClass. Perhaps, for instance, you decide that another field inMyClassneeds to be updated whenevervaluechanges. This would be very difficult to implement without error if accesses tovaluewere scattered everywhere in your code (and nigh-on impossible if your code served as a library for someone else’s code).Additional benefits are that you can, if necessary, rewrite
getValue()andsetValue(int)to synchronize access to the value, to log writes tovalue, or do any number of other things.