Tuesday, July 17, 2012

Encapsulation and Abstraction

Encapsulation and abstraction are two terms that are frequently confused. In reality they complement each other i.e., one cannot exist without the other.


Encapsulation

Internal data of a class should not be exposed to the outside world.

To effectively hide the class fields, we should implement properties like get, set.

We should not have public fields in a class but rather we should go with private fields exposed by public properties to implement encapsulation of data.

So the internal data of the class is encapsulated in the class with the methods that expose them.

By making members private, we hide the complex things from the outside world. This process of hiding is called encapsulation. It achieves abstraction i.e., the outside client sees only the simple stuff that was not hidden.


Abstraction

Abstraction is achieved by encapsulation of data.

The concept of showing only what is necessary and simple for client to understand - is called abstraction.

Only the minimal things that are actually needed by the client code need to be exposed.

This abstraction is done by encapsulation using keywords such as private, protected, public etc.

Internal workings of the class are abstracted from the client.

No comments:

Post a Comment