Let assume a person is giving a talk to more than 500 people when he suddenly realizes he was naked. It’s really awful situation. It is same for an object too…..
Encapsulation puts a forceful-field around object’s instance variables, so nobody can set them to, let’s say something inappropriate.
Most instance variable values are set with certain assumptions about the boundaries of the values. Encapsulation let you set boundaries, by forcing other code to go through setter methods. That’s why the setter method can validate the parameter and decide if it’s do-able. May be the setter method will reject it and do nothing or maybe it will throw an exception or maybe the method will round the parameter sent into the nearest acceptable value. The point is you can do anything you want in the setter method, whereas you can’t do anything if your instance variables are public.
Imagine if half the people in your company used your class with public instance variables, and one day you suddenly realized, “Oops- there is something I didn’t plan with that value, I’m going to have to switch to a setter method.” You break everyone’s code.The cool thing about encapsulation is that you get to change your mind. And nobody gets hurt.
The point to encapsulation(Remember encapsulation is attained by using setter and getter methods) is that you can change your mind later, without breaking anybody else’s code!
So, encapsulation is nothing but hiding the data.