Friday, October 29, 2010

Difference between Encapsulation & Abstraction

This is a common OOPS related question that is being regularly asked in interviews and though it seems to have an easy answer to it, the actual difference can be a bit tricky. So I thought of just pointing out the main differences that i came to understand.

Encapsulation : In simple words , Encapsulation is data hiding. One of the major fundamentals of a good java design is that a class should have 'low coupling, high cohesion'. To have a low coupling, the calling class should be less dependent on the properties of the class or to say if the property changes it shouldn't change the depending functionalities. Encapsulation also prevents direct data manipulation by hiding the property and only which can be accessed by accessor methods. P.J. Plauger has a great analogy and definition of information hiding.”Information hiding is not the same as secrecy. The idea is not to prevent outsiders from knowing what you are doing inside a module. Rather, it is to encourage them not to depend on that knowledge. That leads to a kind of secondary coupling which is more pernicious than obvios dependency because it is less visible. You should encapsulate information to keep it private, not secret. (What you do in the bathroom is no secret, but it is private.)”

Abstraction : Abstraction is the interface which hides the inner functionality.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. Abstraction can be seen in java esp in the io package where how the string, or byte is being written in the output stream or read from the stream is not the developers concern

No comments:

Post a Comment