Saturday, August 13, 2011

Encapsulation vs Abstraction in OOPs

Encapsulation:

Combining the data (information) and the methods (functions) that can manipulate that data - into one capsule (class/object). Depending on how you write program encapsulation, it guarantees that the encapsulated data is not accessed by any other function/method/program outside the encapsulated object.

We provide public/protected methods via which the encapsulated information can be accessed or changed.

For example,
class MyCapsule
{
private:
int myInt;
char myChar;
public:
MyIntFunc() { myInt = 10; }
MyCharFunc() { myChar = 'A'};
};

In this case, no other program/function/method can access myInt other than MyIntFunc. Same is true for myChar and MyCharFunc.

Abstraction:

To hide actual implementation of an object from the external world that would use the object. Look at it as “what” the method or a module does not “how” it does it.

Let’s compare Java and C++. We have a good example of abstraction. In C++, you have to deal with pointers and references a lot. You have to deal a lot of garbage collection. In essence, you have to work on a low level. (C and C++ in turn abstracted a lot of even lower level machine code.) In Java, those things are abstracted away. You just assume they exist. In essence, abstraction means that you are working on a higher level. You don’t care how pointers work in Java, you just assume that they work. You don’t have to concentrate on the lower level stuff, you work on higher level.

No comments:

Post a Comment