封装和抽象之间的确切区别是什么?
当前回答
有一件事,也许是其他答案忘记提到的一个基本的事情是,封装是抽象。因此,将两者进行对比并寻找差异是不准确的,而应该将封装视为一种抽象形式。
其他回答
封装意味着隐藏数据,比如使用getter和setter等。
抽象意味着-隐藏实现使用抽象类和接口等。
抽象和封装都是用来隐藏数据的。但是有很大的不同。
封装
封装是将数据和对数据进行操作的代码绑定或包装成一个称为Class的单元的过程。
封装在实现级别解决了问题。
在类中,可以使用私有或受保护的访问修饰符来隐藏数据。
抽象
抽象是隐藏无关细节的概念。换句话说,通过对用户隐藏不必要的细节,使复杂的系统变得简单。
抽象在设计层面解决了问题。
可以通过在Java中创建接口和抽象类来实现抽象。
在ruby中,你可以通过创建模块来实现抽象。
示例:我们使用(收集,映射,减少,排序…)方法的枚举模块与数组和ruby哈希。
另一个例子:
假设我创建了一个不可变的Rectangle类,如下所示:
class Rectangle {
public:
Rectangle(int width, int height) : width_(width), height_(height) {}
int width() const { return width_; }
int height() const { return height_; }
private:
int width_;
int height_;
}
现在很明显,我已经封装了宽度和高度(访问受到某种限制),但我没有抽象任何东西(好吧,也许我忽略了矩形在坐标空间中的位置,但这是示例的缺陷)。
好的抽象通常意味着好的封装。
一个好的抽象例子是通用数据库连接类。它的公共接口与数据库无关,非常简单,但允许我对连接做我想做的事情。你看到了吗?这里还有封装,因为类内部必须有所有低级句柄和调用。
让我用简单的代码示例来尝试一下
抽象=数据隐藏+封装
// Abstraction
interface IOperation
{
int GetSumOfNumbers();
}
internal class OperationEven : IOperation
{
// data hiding
private IEnumerable<int> numbers;
public OperationEven(IEnumerable<int> numbers)
{
this.numbers = numbers;
}
// Encapsulation
public int GetSumOfNumbers()
{
return this.numbers.Where(i => i % 2 == 0).Sum();
}
}
让我们以堆栈为例。它可以使用数组或链表来实现。但它支持的操作是推送和弹出。
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.
推荐文章
- 什么是依赖倒置原则?为什么它很重要?
- 为什么在Python方法中需要显式地有“self”参数?
- c#中朋友的对等物是什么?
- 如何在方法中访问“静态”类变量?
- 为什么c#不提供c++风格的'friend'关键字?
- String, StringBuffer和StringBuilder
- 存储库和服务层的区别?
- DDD -实体不能直接访问存储库的规则
- 为什么STL如此严重地基于模板而不是继承?
- 如何在Objective-C中声明类级属性?
- 面向方面编程与面向对象编程
- c++中类似于java的instanceof
- 在python中遍历对象属性
- 将类代码分离为头文件和cpp文件
- 在PHP中使用getter和setter而不是函数或简单的公共字段有什么优点?