What is encapsulation? How does it actually hide data?

后端 未结 7 1810
没有蜡笔的小新
没有蜡笔的小新 2020-12-05 17:11

Searching turns up a simple definition: data hiding.

But, consider the following two examples:

1) First Example:

Class Emp         


        
7条回答
  •  被撕碎了的回忆
    2020-12-05 17:32

    There is more to Encapsulation than data hiding. Encapsulation allows you to keep all the data and the functionality pertinent to an entity with this entity. Levels of visibility of this data is a related, but not identical, concept. E.g. an Employee object caries all employee data and functionality (methods) with it. Note that this is not enforced, but enabled by the OO languages.

    This may sound natural to you if you were born into the OO era, but this was the big leap from Functional Programming to OOP, both conceptual (design) and in languages that support this paradigm.

    Quoting from Wikipedia article:

    In a programming language encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination thereof:

    • A language mechanism for restricting access to some of the object's components.
    • A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.

提交回复
热议问题