Thursday, March 8, 2012

Encapsulation vs Abstraction

Let's first revise OOPS fundamentals

Encapsulation and Abstraction are different concepts
Encapsulation begins much earlier; every method is an encapsulation:
Encapsulation is hiding the implementation details which may or may not be for generic or specialized behavior(s).
encapsulation puts some things in a box and gives you a peephole; this keeps you from mucking with the gears.
point x = { 1, 4 };
point y = { 23, 42 };

int d = distance(x, y);
Here, distance encapsulates the calculation of the (euclidean) distance between two points in a plane: it hides implementation details. This is encapsulation, pure and simple.
abstraction flat-out ignores the details that don't matter, like whether the things have gears, ratchets, flywheels, or nuclear cores; they just "go"
abstraction is the process of generalization: taking a concrete implementation and making it applicable to different, albeit somewhat related, types of data. The classical example of abstraction is C's qsortfunction which sorts data.
The thing about qsort is that it doesn't care about the data it sorts – in fact, it doesn't know what data it sorts. Rather, its input type is a typeless pointer (void*) which is just C's way of saying “I don't care about the type of data” (this is also called type erasure). The important point is that the implementation of qsort always stays the same, regardless of data type. The only thing that has to change is the compare function, which differs from data type to data type. qsort therefore expects the user to provide said compare function as a function argument.
Information hiding:
encapsulation is most often achieved through information hiding, which is the process of hiding all of the secrets of object that do not contribute to its essential characteristics."

Abstraction is thought process, Modeling Term, Show only which is minimal/ necessary Information. Encapsulation is Implementation of abstraction, bringing down complexity