What's the difference between abstraction and encapsulation?

前端 未结 24 1016
攒了一身酷
攒了一身酷 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:07

    In my opinion, both terms are related in some sense and sort of mixed into each other. "Encapsulation" provides a way to grouping related fields, methods in a class (or module) to wrap the related things together. As of that time, it provides data hiding in two ways;

    1. Through access modifiers.

      Purely for hiding state of the class/object.

    2. Abstracting some functionalities.

      a. Through interfaces/abstract classes, complex logic inside the encapsulated class or module can be abstracted/generalized to be used by outside.

      b. Through function signatures. Yes, even function signatures example of abstracting. Because callers only knows the signature and parameters (if any) and know nothing about how the function is carried out. It only cares of returned value.

    Likewise, "Abstraction" might be think of a way of encapsulation in terms of grouping/wrapping the behaviour into an interface (or abstract class or might be even a normal class ).

提交回复
热议问题