Short answer:
1) Data hiding can be achieved without encapsulation, an example of this is a private constant in a class, and this constant is not returned by any "getter".
2) Using an access modifier can hide data and encapsulation. You can achieve encapsulation, but not hide data when exposing data, but only to modify them using getters and setters.
And the long answer:
Hiding and encapsulating data are completely different things, but related concepts. Hiding data is not a leak of implementation information to any user of your class, while encapsulation prevents unexpected data changes.
The best explanation I found from this is in the book Growing Object-Oriented, Test-Driven Systems (p. 49)
What the authors say is that encapsulation is almost always good, but hiding data may not be in the right place, and they give the following example:
- Encapsulate the data structure for the cache in the Loader class
- Encapsulate the application log file name in the PrivacyPolicy class
Both of these sounds sound reasonable until we put them in terms of data hiding.
- Hide cache data structure in Loader class
- Hide application log file name in PrivacyPolicy class
In the cache example, it makes sense to hide it. But with regard to the name of the application log file, it makes no sense to hide it.
source share