What's the difference between abstraction and encapsulation?

前端 未结 24 1111
攒了一身酷
攒了一身酷 2020-12-22 17:16

In interviews I have been asked to explain the difference between abstraction and encapsulation. My answer has been along the lines of

  • Abstraction<

24条回答
  •  借酒劲吻你
    2020-12-22 17:59

    Encapsulation

    Encapsulation from what you have learnt googling around, is a concept of combining the related data and operations in a single capsule or what we could say a class in OOP, such that no other program can modify the data it holds or method implementation it has, at a particular instance of time. Only the getter and setter methods can provide access to the instance variables.

    Our code might be used by others and future up-gradations or bug fixes are liable. Encapsulation is something that makes sure that whatever code changes we do in our code doesn't break the code of others who are using it.

    Encapsulation adds up to the maintainability, flexibility and extensibility of the code.

    Encapsulation helps hide the implementation behind an interface.

    Abstraction

    Abstraction is the process of actually hiding the implementation behind an interface. So we are just aware of the actual behavior but not how exactly the think works out internally. The most common example could the scenario where put a key inside the lock and easily unlock it. So the interface here is the keyhole, while we are not aware of how the levers inside the lock co-ordinate among themselves to get the lock unlocked.

    To be more clear, abstraction can be explained as the capability to use the same interface for different objects. Different implementations of the same interface can exist, while the details of every implementation are hidden by encapsulation.

    Finally, the statement to answer all the confusions until now - The part that is hidden relates to encapsulation while the part that is exposed relates to abstraction.

    Read more on this here

提交回复
热议问题