Interviewer: What is encapsulation and how do you achieve it in Java?
Me: Encapsulation is a mechanism to hide
In general Encapsulation means to bundle similar items, simple as that.
For example, take a Student class where we will have students instance variables and behaviors/methods acting on those instance variables @ one place.
Why it is important? We don't want our code scattered all around in our code Base.
If let say we need to make changes then we need find the variants(of that changes) at all the places. By Bundling similar items we are just avoiding such scenarios and it also helps to make our Bundled code more focused.
It just provides a way to protect your data from the outside world. What it means is, lets say if I made my instance variable public, then anyone can change its state. But if we make our instance variable private/protected then actually we are restricting outside entities from making changes to it.
Now question arises, in what respect are we making our variables protected?
Again we need to understand that Encapsulation is just the container we need to place our similar items.
Its just act like a Black box to outside world. Outside world (I mean to say clients/consumers: using our Student class) don't know the internal details/implementation details of the Student class and actually they should not care about the internal details/implementation details of the class. They just want some methods/APIs so that they can use them in their client application.
So my point is all student related behaviors/variables are placed in a Black box which we are calling it as a class. Now its up to designer of the class what are the elements of the class should be hidden and what should not be hidden from outside world.
Now coming back to the question In Java: we are making our variables private it means they are class protected.If we want our instance variables to be accessible throughout the package then they are package protected. Through out project they are public. So what I mean to say is to hide data you need some sort of container where you will put your data and hide with respect to container.
So what I feel Data Hiding is not possible without Encapsulation. You can't hide your data without putting it in some form of container. Again I'm reminding you that I'm putting this on the Object Oriented Language context.
But yes Encapsulation is possible without hiding your data. Put all things public and you can the see the affect.