封装和抽象之间的确切区别是什么?
当前回答
有一件事,也许是其他答案忘记提到的一个基本的事情是,封装是抽象。因此,将两者进行对比并寻找差异是不准确的,而应该将封装视为一种抽象形式。
其他回答
抽象是广义的术语。即封装是抽象的子集。
Abstraction | Encapsulation |
---|---|
It solves an issue at the design level. | Encapsulation solves an issue at implementation level. |
hides the unnecessary detail but shows the essential information. | It hides the code and data into a single entity or unit so that the data can be protected from the outside world. |
Focuses on the external lookout. | Focuses on internal working. |
Lets focus on what an object does instead of how it does it. | Lets focus on how an object does something. |
Example: Outer look of mobile, like it has a display screen and buttons. | Example: Inner details of mobile, how button and display screen connect with each other using circuits. |
示例:解决方案架构师是创建整个解决方案的高级抽象技术设计的人,然后将该设计移交给开发团队进行实现。 在这里,解决方案架构师充当抽象,而开发团队充当封装。
举例:用户数据的封装(组网)
图片由
Abstraction (or modularity) – Types enable programmers to think at a higher level than the bit or byte, not bothering with low-level implementation. For example, programmers can begin to think of a string as a set of character values instead of as a mere array of bytes. Higher still, types enable programmers to think about and express interfaces between two of any-sized subsystems. This enables more levels of localization so that the definitions required for interoperability of the subsystems remain consistent when those two subsystems communicate. Source
Java示例
两者之间存在差异
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.
让我用简单的代码示例来尝试一下
抽象=数据隐藏+封装
// 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();
}
}
抽象和封装都是用来隐藏数据的。但是有很大的不同。
封装
封装是将数据和对数据进行操作的代码绑定或包装成一个称为Class的单元的过程。
封装在实现级别解决了问题。
在类中,可以使用私有或受保护的访问修饰符来隐藏数据。
抽象
抽象是隐藏无关细节的概念。换句话说,通过对用户隐藏不必要的细节,使复杂的系统变得简单。
抽象在设计层面解决了问题。
可以通过在Java中创建接口和抽象类来实现抽象。
在ruby中,你可以通过创建模块来实现抽象。
示例:我们使用(收集,映射,减少,排序…)方法的枚举模块与数组和ruby哈希。
一种防止特定对象的数据被外部函数故意或意外误用的机制叫做“数据封装”。
在不包括背景细节或解释的情况下表现基本特征的行为被称为抽象