Sandeep Jindal Sandeep Jindal - 9 months ago 82
Java Question

Encapsulation vs Data Hiding - Java

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 Source

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.