Encapsulation vs Data Hiding - Java

Sandeep Jindal picture Sandeep Jindal · Aug 17, 2012 · Viewed 69.4k times · Source

Interviewer: What is encapsulation and how do you achieve it in Java?

Me: Encapsulation is a mechanism to hide information from the client. The information may be data or implementation or algorithm. We achieve this using access modifiers.

Interviewer: This is data hiding. How do we achieve encapsulation in Java?

Me: uummmm

Concrete Question: Other than 'Access Modifiers', what is the way to implement Encapsulation in Java?

Answer

pb2q picture pb2q · Aug 17, 2012

More generally encapsulation refers simply to bundling the data (e.g. of an object) with the operations on that data. So you have a class encapsulating data - fields - along with the methods for manipulating that data.

But encapsulation is also sometimes used in the same way as your answer, and indeed, one of the points of bundling data and methods is to hide the implementation.

I suppose a better answer than just use methods and make all fields private is: use interfaces. This way, operations on an object are purely based on the interface contract, and are in no way tied to the fields or helper methods used to implement that contract internally.