封装和抽象之间的确切区别是什么?


当前回答

抽象—隐藏实现—在设计—使用接口/抽象类

封装—隐藏数据—在开发时—使用访问修饰符(公共/私有)

其他回答

封装意味着隐藏数据,比如使用getter和setter等。

抽象意味着-隐藏实现使用抽象类和接口等。

封装隐藏了实现细节,这些细节可能是通用的,也可能不是专门的行为。

抽象提供了一种泛化(例如,在一组行为之上)。

这里有一个很好的阅读:抽象、封装和信息隐藏,作者是Object Agency的Edward V. Berard。

让我们以堆栈为例。它可以使用数组或链表来实现。但它支持的操作是推送和弹出。

Now abstraction is exposing only the interfaces push and pop. The underlying representation is hidden (is it an array or a linked list?) and a well-defined interface is provided. Now how do you ensure that no accidental access is made to the abstracted data? That is where encapsulation comes in. For example, classes in C++ use the access specifiers which ensure that accidental access and modification is prevented. And also, by making the above-mentioned interfaces as public, it ensures that the only way to manipulate the stack is through the well-defined interface. In the process, it has coupled the data and the code that can manipulate it (let's not get the friend functions involved here). That is, the code and data are bonded together or tied or encapsulated.

抽象:以一种简化的/不同的方式来呈现事物的想法,这种方式要么更容易理解和使用,要么更切合实际。

考虑一个发送电子邮件的类……它使用抽象来向你展示自己作为某种信使,所以你可以调用emailSender。发送(邮件,收件人)。它的实际功能——选择POP3 / SMTP、调用服务器、MIME转换等等,都被抽象了出来。你只看到你的信使。

封装:保护和隐藏对象私有的数据和方法的思想。它更多的是让某样东西独立且万无一失。

以我为例。我把我的心率从世界其他地方压缩起来。因为我不希望其他人改变这个变量,我也不需要其他人来设置它来让我运行。它对我来说至关重要,但你不需要知道它是什么,而且你可能根本不在乎。

环顾四周,您会发现几乎所有您接触到的东西都是抽象和封装的例子。例如,你的手机向你展示了一种抽象的功能,它能把你说的话传达给别人——掩盖了GSM、处理器架构、无线电频率以及其他无数你不理解或不关心的东西。它还封装了来自您的某些数据,如序列号、ID号、频率等。

这一切都使世界成为一个更美好的居住地

抽象和封装的区别。