In interviews I have been asked to explain the difference between abstraction and encapsulation. My answer has been along the lines of
Abstraction allows us to represent complex real world in simplest manner. It is the process of identifying the relevant qualities and behaviors an object should possess; in other words, to represent the necessary feature without representing the background details.
Encapsulation is a process of hiding all the internal details of an object from the outside real world. The word "encapsulation", is like "enclosing" into a "capsule". It restricts clients from seeing its internal view where the behavior of the abstraction is implemented.
I think with above answer the interviewer was convinced, but then I was asked, if the purpose of both is hiding, then why there is a need to use encapsulation. At that time I didn't have a good answer for this.
What should I have added to make my answer more complete?
Encapsulation means hiding the internal details or mechanics of how an object does something. Abstraction is outer layout in terms of design. For Example: - Outer Look of a iPhone, like it has a display screen. Encapsulation is inner layout in terms of implementation.
Abstraction focuses on outside viewing, for example, shifting the car. Encapsulation focuses on internal working or inner viewing, for example, the production of the car. Abstraction is supported in Java with the interface and the abstract class.
The main difference between Encapsulation and Abstraction in C# is that the encapsulation wraps the data and methods into a single unit while abstraction hides the implementation details and only displays the functionality to users. C# is a high-level, general-purpose programming language developed by Microsoft.
Abstraction has to do with separating interface from implementation. (We don't care what it is, we care that it works a certain way.)
Encapsulation has to do with disallowing access to or knowledge of internal structures of an implementation. (We don't care or need to see how it works, only that it does.)
Some people do use encapsulation as a synonym for abstraction, which is (IMO) incorrect. It's possible that your interviewer thought this. If that is the case then you were each talking about two different things when you referred to "encapsulation."
It's worth noting that these concepts are represented differently in different programming languages. A few examples:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With