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


当前回答

抽象和封装都是用来隐藏数据的。但是有很大的不同。

封装

封装是将数据和对数据进行操作的代码绑定或包装成一个称为Class的单元的过程。

封装在实现级别解决了问题。

在类中,可以使用私有或受保护的访问修饰符来隐藏数据。

抽象

抽象是隐藏无关细节的概念。换句话说,通过对用户隐藏不必要的细节,使复杂的系统变得简单。

抽象在设计层面解决了问题。

可以通过在Java中创建接口和抽象类来实现抽象。

在ruby中,你可以通过创建模块来实现抽象。

示例:我们使用(收集,映射,减少,排序…)方法的枚举模块与数组和ruby哈希。

其他回答

封装是抽象的一个例子。封装的全部意义在于抽象函数内部发生的事情,将所有的复杂性简化为一个符号(函数的引用或名称),将函数变成一个黑盒。

在编程中,“抽象”一词是一个命令。当一个类继承了一个抽象类(或接口)时,您将被命令创建一个抽象。

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

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

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

这里的大多数答案都关注于OOP,但封装开始得更早:

Every function is an encapsulation; in pseudocode: point x = { 1, 4 } point y = { 23, 42 } numeric d = distance(x, y) Here, distance encapsulates the calculation of the (Euclidean) distance between two points in a plane: it hides implementation details. This is encapsulation, pure and simple. Abstraction is the process of generalisation: taking a concrete implementation and making it applicable to different, albeit somewhat related, types of data. The classical example of abstraction is C’s qsort function to sort data: The thing about qsort is that it doesn't care about the data it sorts — in fact, it doesn’t know what data it sorts. Rather, its input type is a typeless pointer (void*) which is just C’s way of saying “I don't care about the type of data” (this is also called type erasure). The important point is that the implementation of qsort always stays the same, regardless of data type. The only thing that has to change is the compare function, which differs from data type to data type. qsort therefore expects the user to provide said compare function as a function argument.

封装和抽象是密切相关的,因此您可以认为它们确实是不可分割的。就实际而言,这可能是对的;也就是说,这里有一个不太抽象的封装:

class point {
    numeric x
    numeric y
}

我们封装了点的坐标,但是我们没有实质性地将它们抽象出来,只是在逻辑上对它们进行分组。

这里有一个抽象的例子,它不是封装:

T pi<T> = 3.1415926535

这是一个具有给定值(π)的泛型变量pi,声明并不关心变量的确切类型。诚然,我很难在真实的代码中找到这样的东西:抽象实际上总是使用封装。然而,上面的内容在c++(14)中确实存在,通过变量模板(=变量的通用模板);使用稍微复杂一点的语法,例如:

template <typename T> constexpr T pi = T{3.1415926535};

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

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.

抽象和封装过程都会生成接口。

通过封装生成的接口隐藏了实现细节。

与抽象之前相比,通过抽象生成的接口可以适用于更多的数据类型。