Reputation: 9
I am learning Java and my question is Why to use access specifiers/Modifiers in Java? why we need to use Public, Private, Protected and Default access to class, Method or variables. If I am programmer then Obviously I know everything from program. If I am end user then I don't know what program is? Then from whom I am hiding details? Where the data hiding comes in picture? Please help me with some examples as point of programmer as well as as point of end user.
Upvotes: 0
Views: 347
Reputation: 115
If you do need a practical example, let's say the details of your FB password is stored as a private variable and your LoginID is stored as a protected variable in a FBDetails class... Now anyone can inherit the FBDetails class to get your LoginID but apparently no one can access your password.
Upvotes: 1
Reputation: 972
As point of software designer: practical and semantic reasons.
Variables describe an object instance's state. Protected variables are inherited. This is practical as classes in the inheritance chain can share structural similarities with each other. Non-inheriting variables remain private. Variables are only public when they are constants (public static final variables).
Methods describe an object's behaviour. The inheritance of protected and the usage of public methods is pretty much the same as with variables, except that while variables describe state, methods describe behaviour. One difference is the usage of package private methods, which approach is usually used inside frameworks.
Upvotes: 1
Reputation: 1514
Hiding the internals of the object protects its integrity by preventing users from setting the internal data of the component into an invalid or inconsistent state.
A benefit of encapsulation is that it can reduce system complexity, and thus increases robustness, by allowing the developer to limit the inter-dependencies between software components. [1]
[1] http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)
Upvotes: 2