What's the difference between abstraction and encapsulation?

前端 未结 24 1127
攒了一身酷
攒了一身酷 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 18:08

    Developer A, who is inherently utilising the concept of abstraction will use a module/library function/widget, concerned only with what it does (and what it will be used for) but not how it does it. The interface of that module/library function/widget (the 'levers' the Developer A is allowed to pull/push) is the personification of that abstraction.

    Developer B, who is seeking to create such a module/function/widget will utilise the concept of encapsulation to ensure Developer A (and any other developer who uses the widget) can take advantage of the resulting abstraction. Developer B is most certainly concerned with how the widget does what it does.

    TLDR;

    • Abstraction - I care about what something does, but not how it does it.
    • Encapsulation - I care about how something does what it does such that others only need to care about what it does.

    (As a loose generalisation, to abstract something, you must encapsulate something else. And by encapsulating something, you have created an abstraction.)

提交回复
热议问题