Wednesday 14 December 2016

Difference between data encapsulation vs abstraction

Encapsulation and abstraction both solve same problem: Complexity; but in different dimensions.

Abstraction is virtual class design.
Before actually defining class, developer will think about what all properties,methods and event will be there in my class.At the time of class definition ,developer will think about which should display to end user and which should not
Whereas,encapsulation is data hiding.


Encapsulation is a mechanism by which you restrict the access to some of the object's components, as well as binding the data and methods operating on the data.

Now if we consider a laptop, as an end user I have access only to some features of the  system. So I could use the mouse to move the cursor, or the keyboard for typing text, but I would not have access to the internal components of the laptop. Again the keyboard in turn is bound internally to a set of methods that operate in response to a user action or an event.

Abstraction is the ability to define an object that can represent abstract entities which can work, change state and communicate with other entities.

Let us take the example of our laptop Keyboard itself, here we have a number of Keys, each performing some function dependent on the value given. Now all keys have a certain value, that is accepted by the CPU when you press it. So we create a common object called Key with following methods.
  1. class Key
  2. {
  3. String keyValue;
  4. }
  5. class KeyBoard
  6. {
  7. public void pressKeyDown(Key k)
  8. {
  9. if(k.keyValue==X)
  10. // Do something
  11. }
  12. }


Now we could create Objects of class Key and pass the definition as shown.

  1. Key enter=new Key();
  2. enter.keyValue="Enter";
  3. Key shift=new Key();
  4. shift.keyValue="Shift";
  5. KeyBoard.pressKeyDown(enter);
  6. KeyBoard.pressKeyDown(shift);


Here the classes Key and Keyboard are abstractions used in place of an actual Key and Keyboard.

No comments: