封装和抽象之间的确切区别是什么?
当前回答
简而言之:
抽象是一种帮助我们识别哪些特定信息是必要的,哪些信息应该隐藏的技术。
因此,封装是一种以隐藏对象的细节和实现细节的方式封装信息的技术。
其他回答
让我们以堆栈为例。它可以使用数组或链表来实现。但它支持的操作是推送和弹出。
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.
一种防止特定对象的数据被外部函数故意或意外误用的机制叫做“数据封装”。
在不包括背景细节或解释的情况下表现基本特征的行为被称为抽象
上面提供了很多很好的答案,但我将在这里介绍我的(Java)观点。
数据封装简单地说就是包装和控制类中逻辑分组数据的访问。它通常与另一个关键字-数据隐藏相关联。这是在Java中使用访问修饰符实现的。
一个简单的例子是定义一个私有变量,并使用getter和setter方法访问它,或者将一个方法设置为私有,因为它只在类中使用。用户不需要知道这些方法和变量。
注意:不要误解封装只是关于数据隐藏。当我们说封装时,重点应该是将相关数据和行为分组、打包或捆绑在一起。
另一方面,数据抽象是泛化的概念,这样底层的复杂逻辑就不会暴露给用户。在Java中,这是通过使用接口和抽象类实现的。
的例子,
Lets say we have an interface Animal and it has a function makeSound(). There are two concrete classes Dog and Cat that implement this interface. These concrete classes have separate implementations of makeSound() function. Now lets say we have a animal(We get this from some external module). All user knows is that the object that it is receiving is some Animal and it is the users responsibility to print the animal sound. One brute force way is to check the object received to identify it's type, then typecast it to that Animal type and then call makeSound() on it. But a neater way is to abstracts thing out. Use Animal as a polymorphic reference and call makeSound() on it. At runtime depending on what the real Object type is proper function will be invoked.
详情请点击这里。
复杂的逻辑是在电路板中,封装在一个触摸板中,并提供了一个漂亮的界面(按钮)来将其抽象给用户。
附注:以上链接是我的个人博客。
通过使用单个通用示例进行抽象和封装
------------------------------------------------------------------------------------------------------------------------------------
我们都用计算器来计算复杂的问题!
抽象让您关注对象做了什么,而不是它是如何做的 封装意味着隐藏对象如何做某事的内部细节或机制。
就像你开车时,你知道油门踏板的作用,但你可能不知道它背后的过程,因为它是封装的。
让我用c#举个例子。假设你有一个整数:
int Number = 5;
string aStrNumber = Number.ToString();
你可以使用像number . tostring()这样的方法,它返回数字5的字符表示,并将其存储在字符串对象中。该方法告诉您它做了什么,而不是如何做。
推荐文章
- 什么是依赖倒置原则?为什么它很重要?
- 为什么在Python方法中需要显式地有“self”参数?
- c#中朋友的对等物是什么?
- 如何在方法中访问“静态”类变量?
- 为什么c#不提供c++风格的'friend'关键字?
- String, StringBuffer和StringBuilder
- 存储库和服务层的区别?
- DDD -实体不能直接访问存储库的规则
- 为什么STL如此严重地基于模板而不是继承?
- 如何在Objective-C中声明类级属性?
- 面向方面编程与面向对象编程
- c++中类似于java的instanceof
- 在python中遍历对象属性
- 将类代码分离为头文件和cpp文件
- 在PHP中使用getter和setter而不是函数或简单的公共字段有什么优点?