封装和抽象之间的确切区别是什么?
当前回答
抽象:只显示必要的信息。让我们关注一下在计算机上进行开关的例子。当系统仍在加载时,用户不必知道发生了什么(该信息对用户隐藏)。
让我们再举一个例子,ATM机。客户不需要知道机器如何读取密码并处理交易,他所需要做的就是输入密码,拿现金然后离开。
封装:处理隐藏类的敏感数据,从而私有化类的一部分。这是一种通过不允许外部访问来保持某些信息对其客户端的私密性的方法。
其他回答
抽象和封装过程都会生成接口。
通过封装生成的接口隐藏了实现细节。
与抽象之前相比,通过抽象生成的接口可以适用于更多的数据类型。
抽象让您关注对象做了什么,而不是它是如何做的 封装意味着隐藏对象如何做某事的内部细节或机制。
就像你开车时,你知道油门踏板的作用,但你可能不知道它背后的过程,因为它是封装的。
让我用c#举个例子。假设你有一个整数:
int Number = 5;
string aStrNumber = Number.ToString();
你可以使用像number . tostring()这样的方法,它返回数字5的字符表示,并将其存储在字符串对象中。该方法告诉您它做了什么,而不是如何做。
抽象或封装并不严格要求信息隐藏。信息可能会被忽略,但不一定要隐藏。
封装是一种将事物视为单一事物的能力,即使它可能由许多复杂的部分或思想组成。例如,我可以说我坐在一把“椅子”上,而不是指这把椅子上的许多不同部分,每个部分都有特定的设计和功能,它们精确地组合在一起,目的是让我的屁股舒适地离地板几英尺远。
Abstraction is enabled by encapsulation. Because we encapsulate objects, we can think about them as things which relate to each other in some way rather than getting bogged down in the subtle details of internal object structure. Abstraction is the ability to consider the bigger picture, removed from concern over little details. The root of the word is abstract as in the summary that appears at the top of a scholarly paper, not abstract as in a class which can only be instantiated as a derived subclass.
I can honestly say that when I plop my butt down in my chair, I never think about how the structure of that chair will catch and hold my weight. It's a decent enough chair that I don't have to worry about those details. So I can turn my attention toward my computer. And again, I don't think about the component parts of my computer. I'm just looking at a part of a webpage that represents a text area that I can type in, and I'm communicating in words, barely even thinking about how my fingers always find the right letters so quickly on the keyboard, and how the connection is ultimately made between tapping these keys and posting to this forum. This is the great power of abstraction. Because the lower levels of the system can be trusted to work with consistency and precision, we have attention to spare for greater work.
简而言之:
抽象是一种帮助我们识别哪些特定信息是必要的,哪些信息应该隐藏的技术。
因此,封装是一种以隐藏对象的细节和实现细节的方式封装信息的技术。
让我用简单的代码示例来尝试一下
抽象=数据隐藏+封装
// 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();
}
}