Ads Here

Monday, August 15, 2011

What is Encapsulation

Wrapping up data member and method together into a single unit (i.e. Class) is called Encapsulation.

Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data related to an object into that object.

Encapsulation is like your bag in which you can keep your pen, book etc. It means this is the property of encapsulating members and functions.

    class Bag
    {
        book;
        pen;
        ReadBook();
    }


Encapsulation means hiding the internal details of an object, i.e. how an object does something.

Encapsulation prevents clients from seeing its inside view, where the behaviour of the abstraction is implemented.

Encapsulation is a technique used to protect the information in an object from the other object.

Hide the data for security such as making the variables as private, and expose the property to access the private data which would be public.
So, when you access the property you can validate the data and set it.

Example:

class Demo
{
   private int _mark;

   public int Mark
   {
     get { return _mark; }
     set { if (_mark > 0) _mark = value; else _mark = 0; }
   }
 }

Real world Example of Encapsulation:-

Let's take example of Mobile Phone and Mobile Phone Manufacturer
Suppose you are a Mobile Phone Manufacturer and you designed and developed a Mobile Phone design(class), now by using machinery you are manufacturing a Mobile Phone(object) for selling, when you sell your Mobile Phone the user only learn how to use the Mobile Phone but not that how this Mobile Phone works.

This means that you are creating the class with function and by making object (capsule) of it you are making availability of the functionality of you class by that object and without the interference in the original class.

Example-2: 

TV operation 

It is encapsulated with cover and we can operate with remote and no need to open TV and change the channel.
Here everything is in private except remote so that anyone can access not to operate and change the things in TV.




Related Topics:-

OOPs Concepts
What is Abstraction
What is Encapsulation
What is Inheritance
Polymorphism in .Net
Difference between Abstraction and Encapsulation

1 comment:

JaiDeep said...

Hi Manish

That really a great article in a simplified manner. Really helps to understand from basic point of view.