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


当前回答

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

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

其他回答

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

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.

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

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

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

我认为封装是实现抽象的一种方式。看看下面的链接。

抽象和封装

封装要求模块化。它要求您创建具有数据和处理数据的方法的对象。在这种情况下,您可以将其视为一个模块。

抽象为您提供了类的一般视图。

两者之间存在差异

ABSTRAACTION

and

封装

1.    First difference between Abstraction and Encapsulation is that, Abstraction is implemented in Java using interface and abstract class while Encapsulation is implemented using private, package-private and protected access modifier.

2.    Data abstraction simply means generalizing something to hide the complex logic that goes underneath where Encapsulation is DATA HIDING.


3.    Encapsulation is combining related logic data (variables and methods) where as Abstraction is hiding internal implementation details and expose only relevant details to the user. In a way you can Abstraction is achieved by Encapsulation.