Encapsulation : Wrapping up of data and methods into a single unit is called Encapsulation (e.g. Class)
Abstraction : It is an act of representing only the essential things without including background details. (e.g. Interface)
Real world example
Abstraction : You’ll never buy a “device”, but always buy something more specific : iPhone, Nokia 3310… Here, iPhone, and N3310 are concrete things, device is abstract.
Encapsulation : you’ve got several devices, all of them have got an USB port. You don’t know what kind of printed circuit they have, you just have to know you’ll be able to plug an USB cable onto.
Abstraction is a concept, which is allowed by encapsulation. You can do encapsulation without using abstraction, but if you wanna use some abstraction in your projects, you’ll need encapsulation.
Benefits of Abstraction :
Advantages of abstraction are the hiding of implementation details, component reuse, extensibility, and testability.
When we hide implementation details, we reveal a cleaner, more comprehensible and usable interface to our users.
We are separating our interface from our implementation, and this makes component reuse more practical.
Benefits of Encapsulation :
- In Encapsulation fields of a class can be read-only or can be write-only.
- A class can have control over in its fields.
- A class can change data type of its fields anytime but users of this class do not need to change any code.
We can see the use of Encapsulation by using properties. The property has two accessor get and set. The get accessor returns the value of the some property field. The set accessor sets the value of the some property field with the contents of “value”. Properties can be made read-only. This is accomplished by having only a get accessor in the property implementation.