Who Knows All.. ?

If the answer is No one. Then this blog is for U. I'm going to put all the things I know in Java

What is Encapsulation? Explain briefly?

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s


This entry was posted on November 5, 2011 by in Encapsulation, What is encapsulation.
%d bloggers like this: