I'm trying to figure why people say this is a good way to prevent access to your class file that you don't want but can't I just use reflection to access the class? Isn't obfuscation to prevent unauthorized access better because no one knows what your code does even if they use reflection?
-
As mentioned, encapsulation isn't the same as protecting access. But do read up on the SecurityManager and Java permissions - once the SecurityManager is turned on in the JVM, you can run untrusted code or trusted code with limited permissions, and then it is no longer possible to use reflection to access private members (unless the code has the correct permission) – Erwin Bolwidt Feb 28 '15 at 05:35
3 Answers
The point of encapsulation is to prevent access to your implementation internal classes for the sake of cleaner code, not to technically prevent users of your class from accessing instances using reflection, or decompiling it.
For example, if you have an HTTP client, you should encapsulate the streams and buffers you use, and only expose the request and response to the actual user of your class. This is designed so your--and their--code is cleaner, not so that they can never reflect on your class. Additionally, since the only API users are accessing is the external API, you are free to change the internals of your classes or code as much as you wish.

- 40,330
- 4
- 86
- 117
-
So it is mostly for cleaner code and a bit of preventing access to inter classes? – Joe Feb 27 '15 at 23:44
-
@Joe Yes, it is overall to keep the public API of a library separate from its internals. – nanofarad Feb 27 '15 at 23:45
Encapsulation is a way to communicate to other programmers what they should and shouldn't do with your data. They can always circumvent this, but by making it marginally more difficult, you effectively tell them to be extremely cautious when accessing the encapsulated data, and warn them that you might change your implementation at any time and break any code that relies on it.
Encapsulation is not a DRM-like method of securing your code and data against malicious access.

- 11,360
- 6
- 40
- 54
Encapsulation is not about preventing access to backend code but about representing boundary. It helps the programmer to write code which is scalable and modifiable easily. From here, principles like "separation of concern" will come.

- 82
- 1
- 7